#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    4
    Rep Power
    0

    Red face Precedence/Assositivity between ! and !=


    Hi All,

    I want to know how the following expression will be resolved:

    int j=4;
    (!j!=1 ? printf(“\nWelcome”) : printf(“\nGood Bye”));

    I thought it should do following way but it failed:
    Step 1: ! (j!=1) It should compare the value of j (which is 4) to 1 which are not equal and it returns true i.e. 1

    Step 2: tham it should check !(1) whch should be true i.e. 0

    and it should print Good Bye.

    But programs return Welcome.

    So that means it should go from left to right. but than the question is
    Step 1: (!j)!=1 :: what will be returned for !j as j is an integer as has a value of 1

    Could you please help tounderstand this.

    Thanks and regards.
  2. #2
  3. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,607
    Rep Power
    4247
    It evaluates as though you typed:
    (!j)!=1
    Look at C's operator precedence for details as to why this is so.

    Since j is non-zero, !j evaluates to 0. Then it evaluates 0 != 1, which is true and hence, it prints "Welcome".

    As an aside, if someone uses this in actual code (or even to teach code), feel free to slap them for me.
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    4
    Rep Power
    0

    Red face


    Thanks for your reply.

    Ok would like to ask one more question on precedence.

    how the following expression would be resolved:

    int a = 500;
    if(!a>400)

    Method 1: Will it solve by this rule ((!a)>400) i.e.
    Step 1: a=500 and !a will be 0
    Step 2: than 0>500 which is false and returns 0

    or by
    Method 2 !(a>400)
    Step 1: 500>400 which is true
    Step and !500 is 0 which is false and returns 0

    Could you please help me to understand..
  6. #4
  7. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,143
    Rep Power
    2222
    From a table of precedence, look up ! and look up >. Which one has precedence over the other? That will give you your answer.

IMN logo majestic logo threadwatch logo seochat tools logo