I am having this problem with precedence of operators. Its with the increment and decrement operators.

int i,j=1;
i=(j++)+(++j)+(j++);

this evaluates to 6 instead of 7 . Why does this happen. It would be of great help to me.
Thanks,
comwizz

Member Avatar for iamthwee

j++

means j == j +1

but ++j means add one before u do the next thing i thinks.

God bless.


j++ means j == j +1

I think you ment j = j + 1 right :?:

I am having this problem with precedence of operators. Its with the increment and decrement operators.

int i,j=1;
i=(j++)+(++j)+(j++);

this evaluates to 6 instead of 7 . Why does this happen. It would be of great help to me.
Thanks,
comwizz

It looks like you're expecting the expression (j++)+(++j)+(j++) to be evaluated from left to right. The C standard does not require this. Because you are modifying your variable j more than once in the same expression, the behavior is undefined.

It looks like you're expecting the expression (j++)+(++j)+(j++) to be evaluated from left to right. The C standard does not require this. Because you are modifying your variable j more than once in the same expression, the behavior is undefined.

Even if we evaluate from the right for j=1 the expression will be evaluated like 1 + 3 + 3 and will still turn out to be 7. Do you mean that theres no conventional way of how to evaluate this expression?? If there is a way please do tell me.
Thanks,
comwizz.

Even if we evaluate from the right for j=1 the expression will be evaluated like 1 + 3 + 3 and will still turn out to be 7.

You have no guarantee of when the increments happen. They could happen in the middle of the expression (as when you evaluate left-to-right or something), or they could happen after, or whenever. (k = j++ + j++) might be treated equally as either k = j + j; j += 2; or k = j; j += 1; k += j; j += 1; You need to separate your expression into multiple statements. For another example: Is y[i] = ++i; equivalent to y[i] = i; i += 1; or y[i + 1] = i; i += 1; ?

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.