1

I am a newbie in C++.

A semicolon is a terminator, so when it is included at the beginning of code it must terminate the line, i.e it should skip the line and start executing the next line. When I include a semicolon at the beginning of code, it does not show any error and the line is not terminated.

Please correct me.

Example:

; string a = "5.558";
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
RaHuL
  • 101
  • 1
  • 12
  • 6
    Possible duplicate of [C: why are extra semicolons OK?](https://stackoverflow.com/questions/38870692/c-why-are-extra-semicolons-ok) – dandan78 Oct 17 '19 at 08:18
  • 5
    It's not a terminator ... It's a separator. – Gojita Oct 17 '19 at 08:19
  • Hm... Albeit the actual answer is the same as in the 'duplicate', we are in two different languages. So is this really a duplicate? – Aconcagua Oct 17 '19 at 08:24
  • @Aconcagua i'd say no, unless the other quesiton is retagged as c++ also. However, usually the asker cannot know if the answer is the same in two different languages, so I wouldnt do that, not sure what is the accepted policy though – 463035818_is_not_an_ai Oct 17 '19 at 08:26

2 Answers2

5

You don't get an error because it isn't one. You are terminating an empty statement. That's legal in C++ (and has been in C).

So you're example consists of 2 statements (not one):

<empty> ;
string a = "5.558" ;

This can actually be useful. For instance, the for loop needs 3 expressions (init, condidtion and increment/step). Sometimes you don't want to pass all 3, so this is a legal code as well:

for(;;) {  /* do something in this endless loop */ }

The 2 semicolons inside for are therefore separators for 3 (empty) expressions

Florian Braun
  • 321
  • 1
  • 5
3

There is no notion of "lines" in the c++ language. If you like you can put all your code on a single line (not recommended). If you write

int main() {
    ;     // <--
}

Then in the line marked with the comment you have an empty statement that does nothing. See also here. The quesiton is about statements vs expressions, but it might also help to better understand your issue.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185