C静态变量和初始化 [英] C static variables and initialization

查看:105
本文介绍了C静态变量和初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在此代码中有一个全局静态变量x

If I have a global static variable x like in this code

 #include <stdio.h>
 #include <stdio.h>

 static int x;

 int main(void)
 {

 DO SOMETHING WITH x HERE

 x++;

 }

如果我选择将x初始化为一个值,如

What will be difference if I opted to initialize x to a value first say as in

static int x = 0;  

在输入"main"之前?

before entering "main"?

在我没有为x赋值的第一种情况下,编译器是否暗中知道x将被设置为零,因为它是静态变量?听说我们可以使用静态变量来做到这一点.

In my first case where I didn't assign a value to x, does the compiler implicitly know that x is to be set to zero as it's a static variable? I heard that we can do this with static variables.

非常感谢...

推荐答案

有一个很好的答案简短摘录:

首先在ISO C(ANSI C)中,必须在程序启动之前初始化所有静态和全局变量.如果程序员没有明确地执行此操作,则编译器必须将它们设置为零.如果编译器不执行此操作,那么它就不会遵循ISOC.但是,标准并未明确说明变量的初始化方式.

First of all in ISO C (ANSI C), all static and global variables must be initialized before the program starts. If the programmer didn't do this explicitly, then the compiler must set them to zero. If the compiler doesn't do this, it doesn't follow ISO C. Exactly how the variables are initialized is however unspecified by the standard.

这篇关于C静态变量和初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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