Semicolon in C++?

2020-02-10 01:35发布

Is the "missing semicolon" error really required? Why not treat it as a warning?

When I compile this code

int f = 1
int h=2;

the compiler intelligently tells me that where I am missing it. But to me it's like - "If you know it, just treat it as if it's there and go ahead. (Later I can fix the warning.)

  int sdf = 1, df=2;
  sdf=1 df =2

Even for this code, it behaves the same. That is, even if multiple statements (without ;) are in the same line, the compiler knows.

So, why not just remove this requirement? Why not behave like Python, Visual Basic, etc.

Summary of discussion

Two examples/instances were missing, and a semi-colon would actually cause a problem.

1.

return
 (a+b)

This was presented as one of the worst aspects of JavaScript. But, in this scenario, semicolon insertion is a problem for JavaScript, but not for C++. In C++, you will get another error if ; insertion is done after return. That is, a missing return value.

2

int *y;
int f = 1
*y = 2;

For this I guess, there is no better way than to introduce as statement separator, that is, a semicolon.

标签: c++ c
9条回答
【Aperson】
2楼-- · 2020-02-10 01:57

In C programs semicolons are statement terminators, not separators. You might want to read this fun article.

查看更多
小情绪 Triste *
3楼-- · 2020-02-10 02:06

+1 to you both.

The semi-colon is a command line delimiter, unlike VB, python etc. C and C++ ignore white space within lines of code including carriage returns! This was originally because at inception of C computer monitors could only cope with 80 characters of text and as C++ is based on the C specification it followed suit.

I could post up the question "Why must I keep getting errors about missing \ characters in VB when I try and write code over several lines, surely if VB knows of the problem it can insert it?"

Auto insertion as has already been pointed out could be a nightmare, especially on code that wraps onto a second line.

查看更多
Anthone
4楼-- · 2020-02-10 02:07

I won't extend much of the need for semi-colon vs line continuation characters, both have advantages and disadvantages and in the end it's a simple language design choice (even though it affects all the users).

I am more worried about the suggestion for the compiler to fix the code.

If you have ever seen a marvelous tool (such as... hum let's pick up a merge tool) and the way it does its automated work, you would be very glad indeed that the compiler did not modify the code. Ultimately if the compiler knew how to fix the code, then it would mean it knew your intent, and thought transmission has not been implemented yet.

As for the warning ? Any programmer worth its salt knows that warnings should be treated as errors (and compilation stopped) so what would be the advantage ?

查看更多
登录 后发表回答