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(!...
|
|||||||
| Register | FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
|
|||
|
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? |
|
|||
|
#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. |
![]() |
| Thread Tools | |
|
|
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Puzzled on Output | Adrian | C and C++ | 2 | 05-24-2007 04:30 PM |
| To get Output | Rahulbatra | C and C++ | 1 | 05-10-2007 09:23 AM |
| Control Output | caradoc | DB2 | 3 | 04-09-2007 08:59 AM |
| To achieve Output | Ralph | Linux | 0 | 12-12-2006 03:58 AM |
| C Programming - Managing Input and Output Operations | JobHelper | Career Advice | 0 | 04-15-2006 08:30 AM |