Thread: conditional question

  1. #1
    Registered User
    Join Date
    Mar 2020
    Posts
    91

    conditional question

    Good morning....
    Can someone please tell me the difference between

    if (variable = 0)

    and

    if (variable == 0)


    Thanks

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    One is a comparison, the other is an assignment.

  3. #3
    Registered User
    Join Date
    Mar 2020
    Posts
    91
    I understand that but if I want to check for a value do I use the first or the second....I keep getting confused....

    if (variable & 0x0F) .....Seems to me that here if ANY bit in the lower nibble of variable was set I would execute

    if (variable == 0x0E) .....where as here the variable MUST be 0x0E to execute

    Is this correct?

    So the question begs 0 is 0 wouldn't both of the above statements cause execution if variable was 0?

  4. #4
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Well if you use the assignment operator= in an if() statement the statement will always evaluate to true. If you use the comparison operator== it will evaluate to either true or false, depending on the values used in the comparison.

    For the new post:

    What is the type of variable?

    For bit operations is is sometimes easier to use intermediate variables to check your logic.

    Code:
    value = variable & 0x0F;
    
    cout << value << '\n';
    And remember that in C false is zero and true is everything else (not zero).

    Also this link may be of some help when trying to figure out bitwise operations.

  5. #5
    Registered User
    Join Date
    Mar 2020
    Posts
    91
    Here is an unsigned int returned from a function (within a structure)...I am trying to test to see if ANY one of the bits has been set not sure whether to use & or &&???

    Code:
    (swInfo.twoSec & 0x00FE)

    Just figured it out ...thank you!
    used the debugger to see the difference
    Last edited by ridgerunnersjw; 05-05-2020 at 12:25 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to use conditional?
    By abhi143 in forum C Programming
    Replies: 5
    Last Post: 02-22-2020, 08:45 AM
  2. C programming question on Conditional Expressions!
    By n00brammer in forum C Programming
    Replies: 1
    Last Post: 09-20-2015, 11:42 PM
  3. Question about conditional operators ( || vs |)
    By patishi in forum C Programming
    Replies: 2
    Last Post: 10-06-2013, 04:25 AM
  4. conditional
    By bazzano in forum C Programming
    Replies: 9
    Last Post: 03-25-2006, 10:36 AM
  5. Conditional Compile Question
    By nobbyv in forum C Programming
    Replies: 1
    Last Post: 12-05-2005, 10:19 AM

Tags for this Thread