why putting 2 semicolon is not an error?

时间:2016-04-04 16:40:35

标签: c++

I just find out that no matter how many semicolons (if more than 0) the compiler will compile without error

#include <iostream>

int main()
{
   int x;
   x = 5;;
   std::cout << x;;; 
}

will just works fine, so why?

5 个答案:

答案 0 :(得分:5)

It's not an error because the language standard says so. It's OK to have empty statements, they do nothing, and are harmless.

There are times when it's useful:

#ifdef DEBUG
#include <iostream>
#define DEBUG_LOG(X) std::cout << X << std::endl;
#else
#define DEBUG_LOG(X)
#endif

int main()
{
  DEBUG_LOG(1);
}

When DEBUG is not defined this will expand to:

int main()
{
  ;
}

If you couldn't have empty statements that would not compile.

答案 1 :(得分:3)

The semicolon is a terminal, a token that terminates something. What exactly it terminates depends on the context. For example, a semicolon character is at the end of the following parts of the C++ grammar (not necessarily a complete list):

an expression-statement
a do/while iteration-statement
the various jump-statements
the simple-declaration

Note that in an expression-statement, the expression is optional. That's why a 'run' of semicolons, ;;;;, is valid in many (but not all) places where a single one is.

答案 2 :(得分:2)

A semicolon terminates a statement, consecutive semicolons represent no operation / empty statement.

No code will be generated for empty statement.

答案 3 :(得分:1)

If you have two consecutive semicolons, there is an empty statement between them (just another way of saying: there is no statement between them). So, why are empty statements allowed?

Sometimes you need to use some construct, where the language expects a statement, but you dont want to supply one. For example, a common way to write a infinite loop is like this

for (;;) {
    // do something
    // ...and break somewhere
}

If c++ didnt allow empty statements, we would have to put some dummy statements instead of naked ;; just to make this work.

答案 4 :(得分:0)

When you have ;;; in between you have empty statements. Remember C++ doesn't care about white space.

相关问题