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 conclusion
0 50 0
I'm not sure I understand how the first printf value comes to 0 . When the value of k compared to 35 , it should ideally return (and therefore print) 1, but how does it print 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 to 40 . Since 35 < 40 , so it prints 0.
Any help would be appreciated, thanks.
** UPDATE **
After a more detailed study of this topic, as well as on undefined behavior , I came across this in a book in C, the source code is given at the end.
Calling a convention A calling convention indicates the order in which arguments are passed to a function when the function is called. There are two possibilities:
- Arguments can be passed from left to right.
- Arguments can be passed from right to left.
The C language follows the second order.
Consider the following function call:
fun (a, b, c, d ) ;
In this call, it does not matter whether the arguments are passed left to right or right to left. However, in some function call, the order in which the arguments pass becomes an important consideration. For instance:
int a = 1 ; printf ( "%d %d %d", a, ++a, a++ ) ;
It looks like this printf( ) outputting 1 2 3 . However, it is not. Surprisingly, it outputs 3 3 1 .
This is because the Cs calling convention is from right to left . That is, firstly, 1 is passed through the expression a++ , and then a increases by 2 . Then the result is ++a . That is, a increases to 3 , and then it is transmitted. Finally, the last value of a , i.e. 3 is transmitted. So in right to left order 1, 3, 3 is passed. As soon as printf( ) collects them, it prints them in the order in which we asked him to print them (and not the order in which they were transferred). Thus, 3 3 1 is 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 useful to me, so I decided to share it. Note. This also confirms the application submitted by Mr. Zurg in the comments below.