Reputation: 95
I'm learning C++ and I encountered 2 different types of writing a piece of code, and I wanted to know what the difference is.
Is there any difference between:
if(z==true)
{
cout << "Yes";
}
else
{
cout << "NO";
}
and:
if(z==true)
cout << "YES";
else
cout << "NO";
Upvotes: 3
Views: 172
Reputation: 12806
Technically no, but one is IMO better practice. If you omit the brace only the next line is executed, as opposed to executing everything within the brace. You can see how a quick change of code could raise problems.
Say you have
if(z==true)
cout << "YES";
else
x = 47;
and you modify it to
else
x = 47;
y = 99;
y = 99; is executed unconditionally. It's best to avoid these gotchas and just use the braces.
Upvotes: 8
Reputation: 9124
There is no difference at all, the first example has a block of code instead of a single statement, its just a block with a single statement in it. The former is generally considered safer to write.
Upvotes: 2
Reputation: 108800
This code behaves in the same way. So this is only a stylistic issue.
Many programmers prefer the first since it's more robust. It's easy to change the second one in a way that doesn't work as expected. The {}
are necessary if there are multiple statements(or no statement). So changes to the second one can easily result in code where one thinks that a part is conditional/unconditional where it's not. Especially when being sloppy with indentation.
Personally I think if you have a good IDE that can auto format code the risk is small.
Upvotes: 2
Reputation: 69260
No, there is no difference between those two. The {}
are only needed if there are multiple statements, but some people argue that always having them reduces the risk for strange bugs if more statements are added later.
Upvotes: 6