Search code examples
cif-statementcurly-braces

I would like to understand the logic behind the output


#include<stdio.h>
int main()
{
    int value = 0 ;

    if(value)
    
    printf("0");
    printf("1");
    printf("2");

    return 0;
}

The output of the above code is 12 but when I tweak the code by adding curly brackets the output differs

#include<stdio.h>
int main()
{
    int value = 0 ;

    if(value)
    {
    printf("0\n");
    printf("1\n");
    printf("2\n");
    }

    return 0;
}

After adding curly brackets I didn't get an output.

When I change the declared variable to 1 I expected the program to only output the line printf("2") because when the value = 0 it gave 12 as the output excluding the first printf statment, So I expected changing the assigned variable value = 1 as the output would exclude both the first and second printf statments, but it didn't. This made me more confused.

Summary: If there is no curly bracket{} in the code it gives a different output for the same code with curly brackets When I declare value=1 or any other number program prints 012(in both codes). I would like to know why is this happening.

Thank you.


Solution

  • When you see

    if ( condition )
        stuff
    

    it means "if condition is true, do stuff". But you have to be clear on what the condition is, and what the stuff is.

    In C, the condition can be any expression, any expression at all. It can be a number like 0, or a variable like value, or a more complicated expression like i > 1 && i < 10. And, super important: the interpretation of the value is that 0 means "false", and anything else — any other value at all — means "true".

    And then, what about the stuff? You can either have one statement, or several statements enclosed in curly braces { }. If you have one statement, the if( condition ) part controls whether you do that one statement or not. If you have several statements enclosed in { }, the if( condition ) part controls whether you do that whole block or not.

    So when you said

    if(value)
    printf("0");
    printf("1");
    printf("2");
    

    you had one statement — just one — controlled by the if. If value was 0, it would not print 0. If value was anything other than 0, it would print 0. And then, it would always print 2 and 3, no matter what. That's confusing to look at, which is why people always say that proper indentation is important — if you had written it as

    if(value)
        printf("0");
    printf("1");
    printf("2");
    

    then the indentation would have accurately suggested the actual control flow.

    And then when you said

    if(value)
        {
        printf("0\n");
        printf("1\n");
        printf("2\n");
        }
    

    now all three statements are in a block, so they're all controlled by the if. If value was 0, it won't print anything. If value was anything other than 0, it will print all three.