tags:

views:

11362

answers:

3

Why does the compiler give me the following error message on the provided code: "initializer element is not constant". The corresponding C/C++ code compiles perfectly under gcc.

#import <Foundation/Foundation.h>

const float a = 1;
const float b = a + a; // <- error here

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    // insert code here...
    NSLog(@"Hello, World!");
    [pool drain];
    return 0;
}
+8  A: 

That code will only compile correctly if the const float statements appear somewhere other than the file scope.

It is part of the standard, apparently. It is important that all file-scope declared variables are initialised with constant expressions, not expressions involving constant variables.

You are initialising the float 'b' with the value of another object. The value of any object, even if it is a const qualified, is not a constant expression in C.

dreamlax
can you explain why? Thanks i'm interested
hhafez
@hhafez — In this case 'b' is not initialized with another object, but with another primitive. However, both of them are declared as 'const', and 'b' depends on the value of 'a', which is illegal by the standard.
Quinn Taylor
A: 

I don't have Xcode on my machine here so I can't try my example,

But can you try

#define A (1) 
#define B (A + A)

const float a = A;
const float b = B;
hhafez
your second solution would give the same error... you can't just cast a variable to make it a literal.
Jason Coco
deleted my second solution (only left the first)
hhafez
Be aware that #define expressions are "preprocessor directives", meaning they are replaced in the code before the compiler gets a crack at it. If this does work, it's because you get "const float a = (1);" and "const float b = ((1) + (1));" at compile time. Pretty pointless overall.
Quinn Taylor
+3  A: 

@dreamlax is correct, you can't have a const declaration whose initialization depends upon another (const) variable. If you need one to depend on the other, I suggest creating a variable that you can treat as a constant and initialize it only once. See these SO questions for details:

Quinn Taylor