Exforsys
+ Reply to Thread
Results 1 to 5 of 5

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 ...

  1. #1
    cyrus is offline Senior Member Array
    Join Date
    Apr 2006
    Answers
    128

    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?


  2. #2
    Mukhtar Ahmad is offline Junior Member Array
    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=&#37;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.


  3. #3
    zsk_00 is offline Member Array
    Join Date
    May 2006
    Answers
    38
    #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);
    }


  4. #4
    caradoc is offline Senior Member Array
    Join Date
    Apr 2006
    Answers
    122
    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.


  5. #5
    arun17 is offline Junior Member Array
    Join Date
    Oct 2010
    Answers
    6

    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



Latest Article

Network Security Risk Assessment and Measurement

Read More...