
- Forum
- Programming Talk
- C and C++
- Different Output
Different Output
This is a discussion on Different Output within the C and C++ forums, part of the Programming Talk category; My C program is as below: #include <stdio.h> main() { int x=900,y=400,z=0; if(!x>=1000) y=500; z=100; printf("y=%d z=%d",y,z); } I thought ...
-
Different Output
My C program is as below:
#include <stdio.h>
main()
{
int x=900,y=400,z=0;
if(!x>=1000)
y=500;
z=100;
printf("y=%d z=%d",y,z);
}
I thought the output would be
y=500 z=0
But to my surprise the output was
y=400 z=100
Why is it so?
-
05-31-2007, 12:56 AM #2
- Join Date
- May 2007
- Answers
- 12
#include <stdio.h>
main()
{
int x=900,y=400,z=0;
if(!x>=1000)
y=500;
z=100;
printf("y=%d z=%d",y,z);
}
I thought the output would be
y=500 z=0
But to my surprise the output was
y=400 z=100
It the place where operator precedence and associativity come to play its part. in the if condition ((!x>=1000) !x is evaluated first then ( result of !x>= 1000) eventually resulted as false .
as condition is applied to only one statement i.e. y=500; which will not be processed in the very case.
You have the result as it displayed.
-
#include <stdio.h>
main()
{
int x=900,y=400,z=0;
if(!x>=1000) // condition is true
y=500; // ok as this is part of if statement and contion is true
z=100; // this will always be executed as its not part of if statement.
printf("y=%d z=%d",y,z);
}
so
y=500 and z=100 is what you should get.
The following will give what you were expecting.
#include <stdio.h>
main()
{
int x=900,y=400,z=0;
if(x>=1000) { // note that ! have been removed
y=500;
z=100;
}
printf("y=%d z=%d",y,z);
}
-
The evaluation of the statement
if(!x>=1000)
takes place as follows:
Since the precedence of ! is greater than >= it gets evaluated first and so !x is evaluated first. Since x=900 !x results in 0 and 0>=1000 becomes false and so statement jumps to z=500 and your y value remains the same as 400.
-
UR output
the program works correctly. You implemented the program as wrong one.
if you need y=500,z=0
then you want to put else after y=500 in your program.
Last edited by arun17; 10-28-2010 at 07:56 AM.
-
Sponsored Ads

Reply With Quote





