Thread: best practice for nested if stements ie - if x is true and y is true, then...

  1. #1
    Registered User
    Join Date
    Aug 2018
    Posts
    2

    best practice for nested if stements ie - if x is true and y is true, then...

    Hi all. I have a basic question about syntax for nested if statements and use of brackets.

    Let's say I want to perform the following logic...
    If a is greater than b , and a is also greater than c , then let x equal a.

    Here is the code I have tried with no brackets.
    Code:
     if(a > b) if (a > c) x = a;
    Here is the code using brackets:
    Code:
    if(a > b) 
    {
        if(a > c) x = a;
    }
    Will these two produce different results?
    The answer is not obvious with my searches, but on-line compilers seem to work either way. I will be using this in GCC for embedded. Thanks for your help ?

    Cheers,

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Will these two produce different results?
    No, but you may want to consider using a single if statement with multiple conditions.

    Code:
    if(a > b && a > c)
       x = a;
    You may also want to consider using braces for all of your control statements, even simple single liners.

    Also what happens if both conditions are false?

  3. #3
    Registered User
    Join Date
    Aug 2018
    Posts
    2
    Thanks, jimblimberg. If both conditions are false then x is 0, so i assume i would include ...
    Code:
     else x = 0;
    within the same braces, or as per your suggestion.

    Cheers,

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Is this really true ?
    By manasij7479 in forum General Discussions
    Replies: 48
    Last Post: 11-21-2011, 01:22 PM
  2. x = x < y < 2; WHY IS THIS ALWAYS TRUE!?
    By sh4k3 in forum C Programming
    Replies: 5
    Last Post: 06-08-2007, 01:00 AM
  3. It's true and I'm not sorry
    By Lurker in forum A Brief History of Cprogramming.com
    Replies: 9
    Last Post: 02-13-2006, 03:41 AM
  4. Is this true about Dev-C++?
    By RealityFusion in forum Tech Board
    Replies: 7
    Last Post: 08-22-2003, 03:40 PM
  5. is it true
    By Klinerr1 in forum C++ Programming
    Replies: 3
    Last Post: 07-16-2002, 02:21 AM

Tags for this Thread