本文介绍了只能在变量中“声明"变量.全局,但不能修改/(单独初始化)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

免责声明:

  • 这可能是一个非常琐碎的问题(尽管我找不到答案),并且
  • 一个纯粹的理论问题(我从来不需要这样做,也从来没有见过使用这种结构的代码,但是我很好奇这种方式是/为什么发生的.)
  • C/C++双重标记,因为我在C和C ++上都测试了一下代码,它只是4行代码(而且唯一的区别是gcc/clangg++/clang++时发出警告给出一个错误.)
  • This might be a very trivial question (although I cannot find an answer for it), and
  • a purely theoretical question (I never needed to do this, nor ever saw code that uses such constructs, but I am just curious how/why this happens the way it does.)
  • The C/C++ double tag, because I tested the bit of code on both C and C++ and it is just 4 lines of code (and the only difference is that gcc/clang give a warning while g++/clang++ give an error.)

背景:在回答另一个问题时,我开始了考虑一下OP为什么不能修改一个public static变量.我考虑了一下,然后进一步减少了问题,可以看到相同的效果,但不需要任何类或静态成员变量.

Background:In replying to another question, I started to think about why the OP can not modify a public static variable. I thought about it a bit and then reduced the problem a bit further, where I can see the same effect, but without needing any class or static member variables.

问题:然后以下代码可以重现观察结果.

Question: Then the following code can reproduce the observation.

int global_n; // I know it can be initialized right away here also: int global_n = 1;
global_n = 2; // This does not compile in C++. In C it gives a warning about missing type-specifier

int main() {
    global_n = 2; // This does compile in both C/C++ of course
}
  1. 这使我想到了一个问题:全局变量(因此是static变量/成员变量)只能在声明它们时直接在那里初始化.但是任何后续修改只能在函数内部进行.正确吗?

  1. Which brings me to my question: Global variables (and hence static variables/member-variables) can only be initialized, directly there when they are declared. But any subsequent modifications can only occur inside a function. Correct?

是否有任何特定原因?

推荐答案

在函数之外,您不能有语句(即可执行的代码行),只有声明和定义.

Outside of a function, you cannot have statements (i.e. executable lines of code), only declarations and definitions.

对于在全局范围内的global_n = 2;,C90具有一个遗留功能,即如果声明的变量没有类型,则其默认类型为int(C99删除了该功能并需要一个类型).这就是这种情况,这也是为什么您收到有关类型丢失的警告的原因.

In the case of global_n = 2; at global scope, C90 has a legacy feature that if a variable is declared without a type then the has a default type of int (C99 removed the feature and requires a type). That's what's happening in this case, and that's also why you get a warning about the type missing.

C ++没有该规则,因此它显示为函数之外的语句,这是错误的.

C++ doesn't have that rule, so this appears as a statement outside of a function which is an error.

这篇关于只能在变量中“声明"变量.全局,但不能修改/(单独初始化)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 22:29
查看更多