Monday, May 16, 2011

Always write if statements with braces

By putting braces around every block of code you write, you ensure that future edits won't introduce bizarre bugs.
If you have a one-line if statement:
if(<condition>)
    execute();


you should still surround
execute();


with braces:
if(<condition>)
{
    execute();
}


Now, if you go back and add a second instruction
if(<condition>)
{
    execute();
    execute2();
}


you don't have to worry about putting in the braces, and you know that you won't forget to put them in.



Put braces around if statement code, part 2

 


Try out this little program and you will realise that braces need to be put after the if statement.
 
 int main()
{
    int a=0;
    if(a!=0)
        #define a 5
        printf("%d",a);
    return 0;
}