Mark McIntyre <ma**********@spamcop.net> writes:
On 21 Apr 2006 22:48:11 -0700, in comp.lang.c , ni*****@gmail.com
wrote: I have seen that the following code compiles in some environments
like devc++ but fails on some env's like gcc on linux.
Can someone tell if "int *au=malloc(sizeof(int)*10);" is a constant
expression and can be used in global namespace/file scope.
Which part of the standard says or describes this .
#include<stdio.h>
#include<stdlib.h>
int *au=malloc(sizeof(int)*10);
In C, you can't have runtime-evaluated statements outside a function.
Mark McIntyre
Right, but "int *au=malloc(sizeof(int)*10);" is a declaration, not a
statement.
Any object declared outside a function has static storage duration.
The constraint you're running into here is C99 6.7.8p4:
All the expressions in an initializer for an object that has
static storage duration shall be constant expressions or string
literals.
A function call (malloc(), in this case) cannot be a constant
expression.
Keep in mind that "constant" and "const" are very different things in
C. "const" is a type qualifier that specifies that a declared object
is read-only, though its initial value can be determined dynamically
at run time. A "constant" is a literal, such as 42; a "constant
expression" is (more or less) an expression made up of constants,
whose value can be determined at compile time. The use of such
similar terms is unfortunate.
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.