Objective-C error: initializer element is not constant

objective c

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;
}

Best Answer

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.