Find the answer to your Linux question:
Results 1 to 4 of 4
Hi all, Please take a look at the following code snippet. int x = 0, y = 5, z; z = x && (y = 10); The value of y ...
  1. #1
    Just Joined!
    Join Date
    Jan 2009
    Posts
    12

    How is the following expression evaluated?

    Hi all,

    Please take a look at the following code snippet.

    int x = 0, y = 5, z;

    z = x && (y = 10);

    The value of y after the evaluation of the above statement is 5.

    My question is: Why isn't it 10?

    () have a higher precedence than &&, in which case y = 10 should be evaluated before the && operator is.

    So according to me the following should have happened
    1) y = 10
    2) x && y => 0 && 10
    3) z = 0
    leaving the value of y to be 10

    But why is y being 5 after? Why is GCC being weird?

    Thank you.

  2. #2
    Linux Enthusiast gerard4143's Avatar
    Join Date
    Dec 2007
    Location
    Canada, Prince Edward Island
    Posts
    714
    Try compiling with the -S switch and see what was assembled...

    gcc -S filename
    Make mine Arch Linux

  3. #3
    Linux Newbie
    Join Date
    Sep 2004
    Location
    UK
    Posts
    160
    Best guess it's doing a short circuit evaluation because && is a logical operator, probably caused by optimizations. try turning off optimzations.
    In a world without walls and fences, who needs Windows and Gates?

  4. #4
    Linux Enthusiast gerard4143's Avatar
    Join Date
    Dec 2007
    Location
    Canada, Prince Edward Island
    Posts
    714
    Quote Originally Posted by blinky View Post
    Best guess it's doing a short circuit evaluation because && is a logical operator, probably caused by optimizations. try turning off optimzations.
    If you try switching around the terms it works as expected...

    (y = 10) && (z = x);

    so it probably is a short circuit problem
    Make mine Arch Linux

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...