0

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;
        };

    };
};
JaMiT
  • 14,422
  • 4
  • 15
  • 31
peter--
  • 3
  • 1
  • I recommend you pick up a nice C++ book which explains things like this in detail. You can see [this](https://stackoverflow.com/a/388282/10147399) list. I personally recommend [C++ Primer](https://www.amazon.com/dp/0321714113). Good luck! – Aykhan Hagverdili Feb 28 '21 at 21:39
  • 1
    Semi-colons are a punctuator, they denote the end of a statement. The example you have shown are redundant uses of semi-colons. – Mansoor Feb 28 '21 at 21:40
  • Thanks a ton - I’ll get the book.. – peter-- Feb 28 '21 at 21:48

1 Answers1

1

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++)) ;
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953