函数中的静态变量不适用于C而是C ++ [英] Static variable in function not work in C but C++

查看:77
本文介绍了函数中的静态变量不适用于C而是C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的......这个问题让我发疯了......

但代码很简单,我确实已经谷歌了。



代码:



Okay...This problem is driving me crazy...
but the code is pretty easy, and I did already google it.

Code :

void f(int c) {
	static int foo = c;
}





这是我用Google搜索的ed



C中的静态与C ++中的静态之间的区别? - 堆栈溢出 [ ^ ]



它表示C中的静态与'C ++'相当。

但我的编译器只是继续说





Here is what I googled"ed"

Difference between static in C and static in C++?? - Stack Overflow[^]

It says static in C is 'equalvalent to' C++.
but my compiler just keep saying

"Initializer element is not constant"



和我也谷歌它,它只是一直在说常量问题....

但是'const'不是我想要的,我只需要保留变量'foo'!



我尝试过:



Google


and also I did google it, it just keeps saying the 'constant' problem....
but 'const' is not what I want, I just need to reserve the variable 'foo' !

What I have tried:

Google

推荐答案

静态与C / C ++之间的等价更相似......



这里是对你的解释'看到:

在C-GeeksforGeeks中初始化静态变量 [ ^ ]



C中的初始化顺序意味着必须从常量定义静态(这并不意味着该值必须保持不变)。这个要求不是在C ++中,因为初始化顺序在C ++中有点不同,静态不再在main之前初始化,而是第一次遇到它们(对于函数体中的静态而言)。
Statics are more "similar" than "equivalent" between C/C++....

Here's an explanation of what you're seeing:
Initialization of static variables in C - GeeksforGeeks[^]

The initialization order in C means that the static must be defined from a constant (it doesn't imply that the value has to remain constant). This requirement isn't in C++ because order of initialization is a bit different in C++ and static no longer get initialized before "main" but rather the first time they're encountered (for statics in the body of a function anyway).


错误信息清楚地告诉你出了什么问题。您正在尝试从编译时未知的值初始化静态常量。
The error message is clearly telling you what is wrong. You are trying to initialise a static constant from a value that is not known at compile time.


对于C,静态变量只能使用常量值初始化,但函数参数不是常量。 br />


在您的情况下,解决方案非常简单。将命令拆分为初始化和赋值:

With C, static variables can be only initialised with constant values but function parameters are not constant.

The solution is quite simple in your case. Split the command into an initialisation and an assignment:
void f(int c) {
    static int foo = 0;
    foo = c;
}


这篇关于函数中的静态变量不适用于C而是C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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