Objective-C错误:初始化器元素不是常量 [英] Objective-C error: initializer element is not constant

查看:102
本文介绍了Objective-C错误:初始化器元素不是常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么编译器在提供的代码上给我以下错误消息:初始化元素不是常量".相应的C/C ++代码在gcc下可以完美地编译.

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

推荐答案

仅当const float语句出现在文件范围之外的其他地方时,该代码才能正确编译.

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.

您正在用另一个对象的值初始化浮点数'b'.任何对象的值,即使它是const限定的,也不是C中的常量表达式.

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.

这篇关于Objective-C错误:初始化器元素不是常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆