Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there is no compilation or run-time error in the below code?

Tags:

c++

c

compilation

I have below discovery by chance. The compiler compiles the below code without any error or warning. Please help me understand why the compiler is not throwing any error? The program contains just a string in a double quotation.

I have not declared any char array neither assigned the below string to any variable.

void main()
{
    "Why there is no error in compilation?";
}
like image 363
pkthapa Avatar asked Dec 31 '25 21:12

pkthapa


2 Answers

Because any expression is a valid statement.

"Why is there no error in compilation?";

is a statement that consists of an expression that evaluates to the given literal string. This is a perfectly valid statement that happens to have no effect whatsoever.

like image 135
J Earls Avatar answered Jan 02 '26 13:01

J Earls


Of course, "useful" statements look more like

a = b;

But well;

b;

is also a valid statement. In your case, b is simply string literal; and you are free to place that within a the body of a method. Obviously this statement doesn't have any side effects; but what if the statement would be something like

"some string " + someFunctionReturningString();

You probably would want that expression to be executed; and as side effect, that method to be called, wouldn't you?

like image 28
GhostCat Avatar answered Jan 02 '26 11:01

GhostCat