0
#include <iostream>

int main() {
    for( int i = 0; i < 5; ++i) {
        std::cout << "Hello" << std::endl;
    };
}

Is there any case that the semicolon after the for loop would affect the program ?

  • 1
    You could add 100 semicolons and it wouldn't have an effect. Would probably result in identical compiled code. – Carcigenicate Jun 06 '17 at 15:19
  • Off topic, but It can be useful inside a `switch` nevertheless. Check the third answer of [this topic](https://stackoverflow.com/questions/92396/why-cant-variables-be-declared-in-a-switch-statement) if it interests you. – Badda Jun 06 '17 at 15:24
  • 1
    Off topic: format your code. – Jabberwocky Jun 06 '17 at 15:27
  • What's going on with the "tau" in the first `std::`? – Quentin Jun 06 '17 at 15:33
  • This doesn't address the question, but do you really need the extra stuff that `std::end` does? `'\n'` ends a line. – Pete Becker Jun 06 '17 at 23:54

3 Answers3

1

The semicolon is an empty expression statement.

From section 6.2 of the C++ standard

The expression is a discarded-value expression (Clause 5). All side effects from an expression statement are completed before the next statement is executed. An expression statement with the expression missing is called a null statement. [ Note: Most statements are expression statements — usually assignments or function calls. A null statement is useful to carry a label just before the } of a compound statement and to supply a null body to an iteration statement such as a while statement (6.5.1). —end note ]

This will be more clear with some reformatting:

#include <iostream>

int main(){
    for(int i=0; i<5; ++i){
        std::cout <<"Hello"<<std::endl;
    }
    ;
}

The presence of this null statement has no effect on the program.

dbush
  • 205,898
  • 23
  • 218
  • 273
0

No.

The semicolon is not even "attached" to the loop; it's just an empty statement sitting there, effectively on its own.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

It doesn't change anything. It just evaluates to an empty statement.

It's completely harmless. Just a bit of pointless clutter.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70