Reputation: 3
I'm learning C++ and generally it has good and clear rules - but I'm a little confused about the rules related to semicolon. The following two examples are working fine - but what is the best practice - and what is the logic behind it?
Example1 (without semicolon):
#include <iostream>
using namespace std;
int main () {
for (int i = 0; i < 10; i++) {
if (true) {
cout << i << endl;
}
}
}
Example2 (with 3x semicolon):
#include <iostream>
using namespace std;
int main () {
for (int i = 0; i < 10; i++) {
if (true) {
cout << i << endl;
};
};
};
Upvotes: 0
Views: 92
Reputation: 882098
Example 2, reformatted:
#include <iostream>
using namespace std;
int main () {
for (int i = 0; i < 10; i++) {
if (true) {
cout << i << endl;
}
/*do nothing*/ ;
}
/*do nothing*/ ;
}
/*do nothing*/ ;
In other words, ;
in this case is simply an empty statement, totally superfluous. It's legal, but about as useful as the statement 42;
, which is also legal :-)
However, it can sometimes be useful in things like (one example of many), though I usually prefer the {}
construct in these cases:
while (performAction(var++)) ;
Upvotes: 1