初始化静态变量与函数调用给出编译错误? [英] initializing static variable with a function call gives compilation error?

查看:109
本文介绍了初始化静态变量与函数调用给出编译错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>
int foo(){
    return 1;
}
int main(void) {
    static int q = foo(); 
    return 0;
}

下面是相同的链接。这是C code和不是C ++。它编译和运行C ++罚款,但不是C。

Here is a link for the same. This is a C code and not C++. It compiles and run fine in C++ but not C.

这code渐渐编译错误。有人可以请解释为什么会得到错误?可以静态成员只有常数值被初始化?在C ++中,我们需要声明它们,它为什么不是在C后,需要定义静态成员?我找不到类似的查询或一个很好的答案的任何线索。

This code was getting compilation error. Can someone please explain why is it getting error? Can static members only be initialized by constant values ? In C++ we need to DEFINE static members after declaring them , why is it not required in C ? I couldn't find any thread with similar query or a good answer.

推荐答案

全局和静态变量只能在编译时已知的常恩pressions初始化。致电富()函数并不构成采用恒定前pression。此外,在该全局和静态变量被初始化顺序没有指定。一般情况下,调用富()将意味着必须有一定的顺序,因为该功能可以合理预期将已经初始化一些其他变量。

Global and static variables can only be initialized with constant expressions known at compile time. Calling your foo() function does not constitute using a constant expression. Further, the order in which global and static variables are initialized is not specified. Generally, calling foo() would mean that there must be a certain order, because the function can reasonably expect some other variables to be already initialized.

IOW,在C,没有你的code的之前执行的main()

IOW, in C, neither of your code is executed before main().

在C ++中有它周围的办法,但不是在C

In C++ there are ways around it, but not in C.

这篇关于初始化静态变量与函数调用给出编译错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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