简体   繁体   中英

Why does this C++ code compile?

Can someone explain to me why the following code compiles? Is it ignored by the compiler?

#include <stdio.h>
int main() {
    1234;
    return 0;
}

The Standard obliges implementers to allow statements even with no apparent effect. This is mainly because through the magic of macros and templates, they're surprisingly easy to come up with.

There is nothing wrong with this code. It's completely legal. It doesn't do anything, but it's completely legal. Your compiler -- with the right warning settings -- may warn you that it's utterly useless, but it's completely compliant.

一个好的编译器会给你一个警告,你有一个没有副作用的语句a(有效的null语句),但是在C / C ++中允许使用null语句,所以不会有编译错误。

You can think of the statement 1234; as similar to the statement getc(); in that both statements "return" (evaluate to) a value, but nothing is done with the return value. The getc() call has the side effect of consuming a character from standard input, so you're more likely to see that in a program than a bare number. But both are legal.

DeadMG has a good note on why it's a good idea to allow this. It's not because 1234 might be defined as a macro (because as far as I know, that's not allowed). It's because, especially with more complex macros, it's easy to end up with a macro that might reduce to some statement that doesn't do anything.

In C (and thus C++), an expression is a statement and is evaluated for its side effects even if the result is discarded. If it doesn't have any side effects, the compiler might find out and optimized it away (very likely in your case), but it must still compile the code.

Of course, any compiler will warn about that if that warning isn't disabled explicitly.

Turn on warnings.
Set warnings to be treated like errors (as they usually are).

Now it will behave as you would expect:

> cat t.cpp
int main() {
    1234;
    return 0;
}
> g++ t.cpp -Wall -Wextra -pedantic -Werror
cc1plus: warnings being treated as errors
t.cpp: In function ‘int main()’:
t.cpp:2: warning: statement has no effect

Its just that default compiler settings are lax

Because 1234 is a constant, it lets you get away with it. Replacing it with 'x' (without declaring variable x) or 'This doesn't compile' should cause it to fail.

Essentially it is an empty statement, so no harm no foul and it discards the code and keeps going.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM