+ 1

Why do If Statements not require semicolons?

And why are semicolons even necessary in the first place?

12th Jun 2017, 1:16 AM
Carlos DV
Carlos DV - avatar
5 Respostas
+ 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).
12th Jun 2017, 1:47 AM
Tamra
Tamra - avatar
+ 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.
12th Jun 2017, 3:20 AM
Tamra
Tamra - avatar
+ 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.
12th Jun 2017, 4:50 AM
Nihar Raote
Nihar Raote - avatar
+ 2
They arent, neither are brackets, but thats just the style of the language ever since C
12th Jun 2017, 1:18 AM
aklex
aklex - avatar
+ 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?
12th Jun 2017, 3:01 AM
Carlos DV
Carlos DV - avatar