Search code examples
cif-statementreturn

What is happening in this C program with an 'empty' if without curly braces and return after new lines?


So I was writing a C function but I had a hard time debugging, and eventually I found the problem was an 'empty' if statement. However, I suspect it isn't empty, as there were no curly braces, and it might just pass newlines until it finds a line of code. If this line is a return, I might think the return is now 'inside' the if. If this is the case, what would happen if the 'if' condition is false? What would the function return? In my original function, it would just return 15 or 16 (when the condition was false) instead of the expected 0 or 1. I leave here a simplified code of what I'm talking about. In this case something stranger happens. It seems it will always return 1 no matter the 'if' condition is satisfied or not. And if we uncomment the 'return 3;' the code works as expected given that the first return would be inside the 'if'. What exactly is happening here?

#include <stdio.h>
int testIf(void){
    if(0)

    return 1;
    //return 3;
}
int main(void){
    printf("%d\n", testIf());
    return 0;
}



Solution

  • Then the very next line of code is considered to be its body.

    So this:

    if(0)
    
        return 1;
    

    has the same effect with this:

    if (0) {
        return 1;
    }
    

    Now as for your, method, because the condition of the if statement is hardcoded to 0, it will always evaluate to false, and the return statement will not execute.

    return 3; won't execute either, since it's commented. So your method will terminate without executing any return statement, despite the fact that it's defined to return an int.

    This code invokes Undefined Behavior (UB), because we cannot tell what value it will return for sure, because it lacks an effective return statement. To you it happened to be 1, today. In my laptop it may be garbage. This code is, therefore, wrong.

    I strongly recommend that you enable your compiler warnings, e.g. by passing Wall and/or Wextra flags when compiling with GCC, in order to get warned for such logical errors.

    Read more in Function returns value without return statement.