Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf("%d %d %d\n",++a, a++,a) output [duplicate]

Tags:

c

printf

Possible Duplicate:
Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)

I'm not able to understand the output of this program (using gcc).

main()
{
  int a=10;
  printf("%d %d %d\n",++a, a++,a);
}

Output:

12 10 12

Also, please explain the order of evaluation of arguments of printf().

like image 678
nowonder Avatar asked Dec 05 '22 05:12

nowonder


2 Answers

The compiler will evaluate printf's arguments in whatever order it happens to feel like at the time. It could be an optimization thing, but there's no guarantee: the order they are evaluated isn't specified by the standard, nor is it implementation defined. There's no way of knowing.

But what is specified by the standard, is that modifying the same variable twice in one operation is undefined behavior; ISO C++03, 5[expr]/4:

Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full expression; otherwise the behavior is undefined.

printf("%d %d %d\n",++a, a++,a); could do a number of things; work how you expected it, or work in ways you could never understand.

You shouldn't write code like this.

like image 158
Carson Myers Avatar answered Dec 07 '22 17:12

Carson Myers


AFAIK there is no defined order of evaluation for the arguments of a function call, and the results might vary for each compiler. In this instance I can guess the middle argument was first evaluated, following by the first, and the third.

like image 43
haggai_e Avatar answered Dec 07 '22 18:12

haggai_e