Hi,
CAn anyone tell me what does the following statement do in C. *p++ = val My understanding is that because ++ and * have right-associativity, it is equivalent to

p++;
*p=val;

Similarly val = *--p is equivalent to

p--;
val = *p;

Is it correct?

Recommended Answers

All 7 Replies

How about writing a test program to test your assertions?

Hi,
CAn anyone tell me what does the following statement do in C. *p++ = val

*p is assigned the value of val and then p is incremented.

My understanding is that because ++ and * have right-associativity

Associativity? I don't even think you got that right if you were trying to say precedence.

Similarly val = *--p

p is decremented and then val is assigned the value of *p .

and you can also use while(*p++) it will increment addr till it meet \0 in a char *

Associativity? I don't even think you got that right if you were trying to say precedence.

Isn't the precedence of * and ++ same, that's why we look for the associativity in *p++ whcih is right to left.

>Associativity? I don't even think you got that right if you were trying to say precedence.
Nope. He got it right, but came to the wrong conclusion. ++ and * (dereference) have the same precedence but are right associative, so ++ is indeed performed first. However, one can't forget that the postfix increment operator evaluates to the value prior to the increment, and the increment itself is a side effect. Thus the expression *p++ = val; is equivalent to:

*p = val;
++p;

This can easily be verified by using the prefix increment in the same order. *++p = val; is equivalent to:

++p;
*p = val;

Perhaps it was just the chart I was looking at the showed postfix at higher precedence than prefix.

Perhaps it was just the chart I was looking at the showed postfix at higher precedence than prefix.

Isn't this another case were we should not depend in the order of precedence between sequence points?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.