开发者

Why does this C++ code compile?

开发者 https://www.devze.com 2023-02-04 15:57 出处:网络
Can someone explain to me why the follow开发者_如何学Going code compiles? Is it ignored by the compiler?

Can someone explain to me why the follow开发者_如何学Going 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 good compiler will give you a warning that you have a statement that has no side effect a (null statement effectively), however null statements are allowed in C/C++ so there will be no compile error.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号