Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf using stack? [duplicate]

Possible Duplicate:
confused about printf() that contains prefix and postfix operators.

I came across a code with the following snippet,

int main()  {
    int c = 100;
    printf("\n %d \t %d \n", c, c++);
    return 0;
}

I expected the output to be 100 & 101 but I get output as

 101     100

Could anyone help me know why?

like image 214
AnotherDeveloper Avatar asked Jul 08 '11 10:07

AnotherDeveloper


3 Answers

The C and C++ standards do not guarantee the order of evaluation of function parameters. Most compilers will evaluate parameters from right to left because that is the order they get pushed on the stack using the cdecl calling convention.

like image 143
Ferruccio Avatar answered Oct 15 '22 22:10

Ferruccio


There is no guarantee whether c on the left, or c++ on the right, will be evaluated first.

The order of evaluation of function parameters is Unspecifeid and hence Undefined Behavior as per the standard.

As per Section 1.9 of the C++ standard:

"Certain other aspects and operations of the abstract machine are described in this International Standard as unspecified (for example, order of evaluation of arguments to a function). Where possible, this International Standard defines a set of allowable behaviors. These define the nondeterministic aspects of the abstract machine."

like image 32
Alok Save Avatar answered Oct 15 '22 22:10

Alok Save


If you had just used printf ("%d\n", c++) or printf ("%d\n", c) the result would have been 100 in either case. Printing both c and c++ in one function call as you did is undefined behavior.

like image 1
David Hammen Avatar answered Oct 15 '22 22:10

David Hammen