Search code examples
cif-statementcurly-bracesnested-if

Are there any exceptions in removing curly braces for an "if" statement?


I am a computer science student, and some time ago our professor explained us that in C language we can remove curly braces when there's only one statement like:

if (a)
  do b

but we can't do something like this:

if(a)
  do b
  do c

because that would be doing more than one statement.

But it also told us that there's an exception about removing curly braces, something we can't do even if it's only one statement. I did a lot of search but the only thing I found is that I can't do that in a do-while loop, but we are talking about if statements, any help?

Edit: we were also talking about nested if statements, maybe it's about that?


Solution

  • You professor is probably talking about a situation like this:

    if (a)
        if (b)
            printf("a and b\n");
    else  // this goes with the inner "if"
        printf("not a\n");
    

    Contrary to what the indentation suggests, the else is not associated with the outer if statement but with the inner if statement. In this case you need to add curly braces to the body of the outer if for the else to be associated properly:

    if (a) {
        if (b)
            printf("a and b\n");
    }
    else
        printf("not a\n");
    

    It's best to always use braces for the bodies of conditional and looping constructs to prevent this kind of ambiguity and the bugs that go with them.