我可以使用函数调用的结果初始化全局变量吗? [英] May I initialize a global variable with the result of a function call?

查看:139
本文介绍了我可以使用函数调用的结果初始化全局变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码合法吗?

int add(int a, int b)
{
    return a + b;
}

int myvar = add(1, 2);

int main() { /* ... */ }

为什么或为什么不呢?

推荐答案

是的。是的,是这样。

静态初始化器可以调用函数,只要它们在范围内即可。

Static initializers may call functions, as long as they're in scope.

[dcl.decl] (2003年措辞,8/2):

[dcl.decl] (2003 wording, 8/2):


初始值也可以在声明器中指定
;初始化程序是在8.5和12.6中讨论的

Initial values can also be specified in a declarator; initializers are discussed in 8.5 and 12.6.

[dcl.init] (2003年措辞,8.5 / 2):

[dcl.init] (2003 wording, 8.5/2):


自动,注册,静态
命名空间范围
的外部变量可以由涉及$ 文字和
先前声明的变量和
的任意
表达式初始化。 功能

(不要被缺少静态变量所误导关键字,具有各种含义。您的变量 myvar 在命名空间范围内声明,因此具有静态存储期限。)

(Don't be misled by the lack of the static keyword, which has all sorts of meanings. Your variable myvar is declared at namespace scope, and thus has static storage duration.)

这篇关于我可以使用函数调用的结果初始化全局变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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