Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What difference between C and C++ prohibits this eclectic code sample from compiling in the latter?

Tags:

c++

c

I was just wandering over the article hello world in C without semicolons and without IF/WHILE/FOR statements

The following code worked in C but not in C++:

int main(int argc, char *argv[printf("Hello, world!\n")]) {}

In C++, I get this error:

error: expected ‘,’ or ‘...’ before ‘argv’|
warning: second argument of ‘int main(int, char*)’ should be ‘char **’ [-Wmain]|
||=== Build finished: 1 errors, 1 warnings ===|

Why it is not working in C++?

like image 980
Forever Learner Avatar asked Jan 04 '12 18:01

Forever Learner


2 Answers

because C++ has no Variable Length Array feature.

the argv parameter in

char *argv[printf("Hello, world!\n")]

is a Variable Length Array.

The expression that specify the size of the array is

printf("Hello, world!\n")

the result of this expression is of type int and is the number of characters transmitted (or a negative value if there is an error);

An array where the expression in the [] is not constant, like in the example the printf expression, is a Variable Length Array. Those arrays also are permitted to be used as the type of a function parameter.

Variable Length Array is a feature introduced in C in C99 and has not been introduced in C++.

like image 167
ouah Avatar answered Oct 12 '22 01:10

ouah


As the error message indicates, main expects char** for its second argument. However, due to array decay rules, the following are both OK:

int main(int argc, char** argv);   // OK
int main(int argc, char* argv[]);  // OK

And, in fact, the following is also equivalent because array decay doesn't care about dimensions:

int main(int argc, char* argv[5]); // OK

However, whereas in C99 arrays may have variable length, this is not the case in C++. So using a non-constant expression for that array dimension — in your case, printf("Hello world\n") — is invalid syntax.

int main(int argc, char* argv[printf("Hello, world!\n")]); // Not OK!

This invalid syntax is confusing the parser and causing this misleading error in your compiler.

If you simplify the code slightly to remove the function-call-expression (but still using a non-constant for array bounds) then you get a far more relevant error message:

int x = 5;
int main(int argc, char* argv[x]) {}
// error: array bound is not an integer constant

Actually, GCC 4.1.2 gives this useful message for your original code, too, so your compiler must be really old... either that or your testcase is broken despite the far newer GCC 4.5.1 yielding the message you posted.

like image 31
Lightness Races in Orbit Avatar answered Oct 12 '22 03:10

Lightness Races in Orbit