I have the following code snippet:
main( )
{
int k = 35 ;
printf ( "\n%d %d %d", k == 35, k = 50, k > 40 ) ;
}
which produces the following output
0 50 0
I'm not sure I understand how the first value of the printf
comes to 0
. When the value of k
is compared with 35
, it should ideally return (and thus print) 1, but how is it printing zero? The other two values that are produced- 50
and 0
are all right, because in the second value, the value of k is taken as 50
, and for the third value- the value of k(which is 35
) is compared with 40
. Since 35 < 40
, so it prints 0.
Any help would be appreciated, thanks.
**UPDATE**
After researching more on this topic and also on undefined behavior
, I came across this in a book on C, source is given at the end.
Calling Convention Calling convention indicates the order in which arguments arepassed to a function when a function call is encountered. There are two possibilities here:
- Arguments might be passed from left to right.
- Arguments might be passed from right to left.
C language follows the second order.
Consider the following function call:
fun (a, b, c, d ) ;
In this call it doesn’t matter whether the arguments are passed from left to right or from right to left. However, in some function call the order of passing arguments becomes an important consideration. For example:
int a = 1 ;
printf ( "%d %d %d", a, ++a, a++ ) ;
It appears that this printf( )
would output 1 2 3
. This however is not the case. Surprisingly, it outputs 3 3 1
.
This is because C’s calling convention is from right to left
. That is, firstly 1
is passed through the expression a++
and then a
is incremented to 2
. Then result of ++a
is passed. That is, a
is incremented to 3
and then passed. Finally, latest value of a
, i.e. 3
, is passed. Thus in right to left order
1, 3, 3
get passed. Once printf( )
collects them it prints them in the order in which we have asked it to get them printed (and not the order in which they were passed). Thus 3 3 1
gets printed.
**Source: "Let Us C" 5th edition, Author: Yashwant Kanetkar, Chapter 5: Functions and Pointers**
Regardless of whether this question is a duplicate or not, I found this new information to be helpful to me, so decided to share. Note: This also supports the claim presented by Mr.Zurg in the comments below.