+ 1
Why do If Statements not require semicolons?
And why are semicolons even necessary in the first place?
5 Answers
+ 12
Semicolons are how the compiler knows when one statement ends and a new one begins. For example, it allows you to do this (plz don't do this):
cout << "Hello, "; cout << "world!"; //Two statements on 1 line
Braces are similar in that they define a block of multiple statements, and when they start and end. if statements have braces around their statements (even if you leave them off, the compiler puts them there).
+ 9
The braces are doing the job instead of semicolons and showing when the if starts and ends. Look at how main() has braces but no semicolon anywhere - if statements are similar to that.
btw I kinda confused you by saying both "code statement" and "if statement", sorry :( "if structure", is what I was looking for, I think.
+ 6
Semicolons are there so that the compilerđ» can know where a statement ends and another starts.
Like @Tamra showed, we can write a whole program on the same line and it will compile and run just fine (provided that it's error free). Although we don't do this since it's hard for human beingsđ¶ to read the code.
We can tell the difference between two statements if they're written on two different lines, however the compiler requires a semicolon. I hope this answers your question about why semicolons are required.âș
Now moving on to your question about 'if' statements, let's take a quick look at the syntax:
if(some_condition) {
//statements;
}
Now notice that we want to execute some statements when the condition given to 'if' statement is true. We put our statements within braces if more than one statement is to be executed. But if we put a semicolon after the 'if' condition, the compiler will think that the 'if' statement ends there. That is not what we want.
And that's why we don't use a semicolon with an 'if' statement.
+ 2
They arent, neither are brackets, but thats just the style of the language ever since C
+ 1
I'm a little confused. Semicolons tell when a statement ends, but I still don't understand why they're not required for If Statements. Unless they're really just not required at all?