Objective-C error: initializer element is not constant

前端 未结 3 1617
悲哀的现实
悲哀的现实 2021-01-17 17:22

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 und

相关标签:
3条回答
  • 2021-01-17 17:59

    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;
    
    0 讨论(0)
  • 2021-01-17 18:00

    @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:

    • Defining a constant in objective-c
    • Constants in Objective C
    0 讨论(0)
  • 2021-01-17 18:06

    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.

    0 讨论(0)
提交回复
热议问题