Cascara
Cascara

Reputation: 103

How to use post/pre increment operators in addition problems?

 main(){

    int x = 256, y = 4;
    printf("%d\n\n", x++ + ++y);   //output = 261
    printf("%d\n\n", x);          // output = 257
    printf("%d", y);              // output = 5

}

Is the final answer 261, because 256 -> 257 (post operator) and 5 -> 5 (pre operator) cause 256 + 5 = 261?

Upvotes: 1

Views: 3342

Answers (2)

Ashish kumar
Ashish kumar

Reputation: 313

It will show UNSPECIFIED behavior

In your case, we can't tell whether x++ will be evaluated first or ++y will be evaluated first. It is compiler dependent.
So don't use expressions involving a combination of post-increment or pre-increment operators in C or C++.

For more information refer to the link:
https://www.quora.com/What-does-an-expression-involving-multiple-post-pre-decrement-increment-operators-evaluate-to-in-C-and-C++#

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 753575

Given:

int x = 256, y = 4;
printf("%d\n\n", x++ + ++y);

In short: The x++ returns the value 256 and then increments x to 257. The ++y increments y to 5 and returns the value 5. The addition, therefore, adds 256 and 5 yielding 261.

Long windedly: The x++ evaluates to the current value of x which is 256 and schedules an increment of x to 257. Similarly ++y schedules the increment of y to 5 and evaluates to the incremented value 5. The addition, therefore, adds 256 and 5 yielding 261. The order in which the terms involving x and y are evaluated is not defined, but both have to be evaluated before the addition (though the increments may not be complete when the addition is evaluated). Because there is a 'sequence point' when the arguments (and the expression denoting the function) have been evaluated but before the function is called, the increments must be complete when printf() is called.

The next two statements print x and y as 257 and 5.

Note that those two printf() operations could be combined into one. Neither could be combined with the first without invoking undefined behaviour. (See Multiple increments and undefined behaviour for more information on this topic.)

So, allowing for the fact that I would not express it quite the way you wrote it, you seem to have the correct explanation.

Also, Standard C has required a return type on all functions for over 15 years now (since C99 was standardized). You should write:

int main(void)

for a main() function that takes no arguments. (See What should main() return in C and C++? for the full details.)

Note that this question only invokes fully defined behaviour (at least, in the printf() statements). It is not asking about multiple increments on a single variable between sequence points.

Upvotes: 4

Related Questions