Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Why is the answer 1 ?

  1. Aug 14, 2011 #1
    Why is the answer "1"?

    Here is a program :

    #include<stdio.h>
    #include<conio.h>
    void main()
    {
    int i,x=10,y=20,z=5;
    clrscr();
    i=x<y<z;
    printf("%d\n",i);
    getch();
    }


    I am getting the answer as "1". Why? Isn't this suppose to give garbage value if not "0" (zero). Also, please tell me the cases when the answer could be a garbage value or a zero. Please give simple examples. And can you tell me why clrscr(); syntax has to be typed after integer (int) declaration? - Or else it will give you an error.
    Thank you very much.
     
    Last edited: Aug 14, 2011
  2. jcsd
  3. Aug 14, 2011 #2

    I like Serena

    User Avatar
    Homework Helper

    Re: Why is the answer "1"?

    Hi pairofstrings! :smile:

    The expression evaluated: i = x < y < z
    is not really a proper expression.

    It is evaluated as: i = ((x < y) < z);
    Since (x < y) is true, this evaluates as: i = (true < z).
    Next true is interpreted as "1", so this evaluates as: i = (1 < z);
    Again (1 < z) is true, so the value stored in the integer i is "1".

    The clrscr() is a non-standard function call that is not necessary.
    Its function is to clear the screen.

    If you had just declared i without giving it a value, it would have been displayed as garbage.
     
  4. Aug 14, 2011 #3
    Re: Why is the answer "1"?

    What happens when (x<y) is false. Is this interpreted as "0" and this is evaluated as i=(0< z);
    then ( 0< z)which is true here since z=5. Now the value of "i" stored is "1" again. Am I right here?

    And if I declared i= nothing and then give a print statement then the value is displayed as garbage?

    #include<stdio.h>
    #include<conio.h>
    void main()
    {
    int i,x=10,y=20,z=5;
    clrscr();
    printf("%d\n",i);
    getch();
    }
    Will this return a garbage value?
     
    Last edited: Aug 14, 2011
  5. Aug 14, 2011 #4

    Borek

    User Avatar

    Staff: Mentor

    Re: Why is the answer "1"?

    Yes.

    In general - yes.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Why is the answer 1 ?
  1. Why 8 bits = 1 Byte? (Replies: 17)

  2. Awk '{$1=$1}1' file.txt (Replies: 11)

Loading...