Click here to Skip to main content
15,887,917 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C++
main()
{
int k=25;
printf("\n %d %d %d",k==25,k=50,k>10);
return 0;
}


my question is why is the output 0 50 and 1
i have problem with the 0 as output should be 1 as the value of k has been defined as 25
plez help

What I have tried:

and its my first question here so plez ignore my faults in asking .....though future directions are politely welcome :)
Posted
Updated 5-Mar-17 17:05pm
v2
Comments
CPallini 6-Mar-17 3:30am    
Have also a look at:
https://en.wikipedia.org/wiki/Sequence_point

You are in a gray zone, this code is unpredictable and will depend on your compiler.
A C compiler id allowed to rewrite your code as it see fit.
Depending on your compiler, your code
C++
int k=25;
printf("\n %d %d %d",k==25,k=50,k>10);

can translate to (I have rewritten the code with 1 operation per line to illustrate the compiler work)
C++
int k=25;
printf("\n %d",k==25); // 1
k=50;
printf(" %d",k); // 50
printf(" %d",k>10); // 1

or in your case
C++
int k=25;
k=50;
printf("\n %d",k==25); // 0
printf(" %d",k); // 50
printf(" %d",k>10); // 1

In C, never use a variable more than once in a line if you also change its value.
 
Share this answer
 
v5
Comments
Richard MacCutchan 6-Mar-17 3:18am    
It is usually because the arguments are pushed onto the stack in reverse order. So we get the following expressions pushed:
k>10 ...  1
k=50 ... 50, and k now has the value 50
k==25 ... 0
Patrice T 6-Mar-17 3:33am    
I know it.
Just wanted to push an easy to understand picture.
CPallini 6-Mar-17 3:28am    
I don't quite understand why someone voted two. Have my 5.
Patrice T 6-Mar-17 3:35am    
Me too.
Thank you.
nv3 6-Mar-17 4:17am    
My 5. Good explanation.
The first argument, k==25, is a comparison expression. The result being either true (1) or false (0). So, the first number you got was false (0).

The second argument, k=50, is an assignment expression. You set the value of k to be 50. The second number is just saying what the value of k is, 50.

The last argument is another comparison expression. Since k is 50 and 50 is greater than 10, you get true (1).


This reeks of a homework question. I certainly hope you get these concepts because you're in serious jeopardy of failing the class without them.
 
Share this answer
 
v2
Comments
Patrice T 6-Mar-17 1:50am    
Hi Dave,
I think the OP already know these concepts.
He is asking explanation on the k==25 being False, which is rather surprising when one read the code.
See my solution.
Dave Kreskowiak 6-Mar-17 8:18am    
Whoops! My bad. I misread the question.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900