Why can I use constants as statements in C?
Why does this program below not show any er开发者_运维知识库ror ?
int main (void) {
"ANGUS";
1;
3.14;
return 0;
}
Each of those statements are expressions that evaluate to a value, which is then discarded. Compare it to if you called a function that returned an int, a char or a float, without using the return value. That's also an expression that evaluates to a value.
It is not uncommon to have functions that return values that the caller may or may not be interested in, like for example where printf("%d", 9001)
returns the number of characters printed. A caller can use the number returned, or they can just ignore it.
If the compiler complained whenever you ignored a return value, you'd have a very noisy build log. Some compilers however diagnose (if sufficient warning flags are enabled) such pointless side-effect-less uses of literals and variables.
It's perfectly valid for a statement in C to be just a value that gets discarded. Most people don't realise that this is exactly what happens when they code up things like:
x++;
printf ("Hello, world\n");
The former is actually an expression which just happens to have the side effect of incrementing the variable after "returning" it.
The latter function call actually returns a value (the number of characters printed) which is also discarded.
From a certain viewpoint, that is no different from the statements:
42;
3 * 12;
other than the fact that they have no side effects which make them useful.
In fact, even x = 1
is an expression where the result is discarded. It is this that makes x = y = z = 0
possible since this is effectively:
(x = (y = (z = 1)));
All of this is detailed in C99, section 6.8.3 Expression and null statements
which says, in part:
The expression in an expression statement is evaluated as a void expression for its side effects, such as assignments, and function calls which have side effects.
It is perfectly valid for a statement to consist of just an expression. Nothing is achieved by doing so in your examples, but it's perfectly valid all the same.
Since in c it's a valid statement but when you use java it will give you compile time error.
Why should it? The first three lines in you main don't do anything and return 0; is a valid expression.
If you use gcc to compile the program try to enable all warnings (with -Wall parameter). This would print warning: statement with no effect [-Wunused-value]
Because it is valid. A string or a number is a valid expression and an expression followed by semi-colon is a statement (also informally known as instruction).
It is also valid in C++ and it does have a hackish use in Visual Studio where you wish to "Find All References" for an enum, you can type the enum on a line by itself terminated with a semicolon and you can use the context menu to find the references.
精彩评论