声明:K& R.

时间:2014-11-06 14:55:57

标签: c variables

我正在阅读K& R的C编程语言第2章:“类型,运算符和表达式”,第2.4节,其中我发现了以下语句:

  

如果有问题的变量不是自动的,则初始化为   在程序开始执行之前,在概念上完成一次,并且   初始化器必须是一个常量表达式。明确地说   每次初始化初始化的自动变量   或阻止它进入;初始化器可以是任何表达式。

以上几行不太明确是什么意思?

5 个答案:

答案 0 :(得分:11)

int a = 5;
int b = a; //error, a is not a constant expression

int main(void)
{
  static int c = a; //error, a is not a constant expression
  int d = a; //okay, a don't have to be a constant expression
  return 0;
}

只有d是自动变量,因此只允许使用其他变量初始化d

答案 1 :(得分:4)

自动变量是一个普通变量。这些变量在堆栈上创建,并且每次都会初始化。例如:

int example_auto(){
    int foo = 0;
    foo++;
    return foo;
}
每次拨打foo时,

0都会初始化为example_auto()。该函数始终返回1.

静态变量是使用static声明的变量,或者是全局变量(在任何函数之外)。与自动变量不同,这些变量在程序启动时(或接近)初始化。例如:

int example_static(){
    static int foo = 0;
    foo++;
    return foo;
}

foo初始化一次。 example_static()第一次调用时返回1,然后是2,然后是3,等等。

答案 2 :(得分:2)

每次输入函数或块时,都会初始化显式初始化的自动变量

除了其他答案之外,自动,顾名思义,还与在运行时处理变量的方式有关。即,在其定义的逻辑块内,其生命将被创建,并在进入和离开时自动销毁。的 Memory is allocated and deallocated automatically within the variable's context 即可。无需显式创建或销毁内存,因为每次输入和退出逻辑块(由{...}定义)时都会执行此操作。因此术语自动

初始值设定项可以是任何表达式。

自动变量可以使用其他先前初始化的变量,常量或表达式进行初始化。

#define MAX 20.0

float d;

int func(void)
{
    int a = 10;  //automatic
    int b = a + 3; //automatic
    float c = MAX; //automatic 
    d = MAX;  //d is a file global, not automatic, 
              //memory created outside of local scope, 
              //memory is not de-allocated when function exits
    static int e = 0; //Not automatic as static gives local variables life 
                      //beyond the function, i.e. outside scope of {...}
                      //memory, and value of e remain when function exits
                      //and between calls

    return 0;
}

答案 3 :(得分:0)

在C块中,您可以定义两种局部变量:static和auto。请注意,local仅表示变量仅在函数内可见。

每次调用函数/块时都会重新创建一个自动变量,并在控件退出函数/块时销毁。然后在每次创建时对其进行初始化。

静态局部变量在程序的整个生命周期中只创建一次。它被摧毁并结束了该计划。并且它在创建的同时被初始化:在程序开始时只有一次(从概念上讲,它可能略有不同)。

答案 4 :(得分:0)

这表明局部变量也称为自动变量可以通过常量或非常量表达式初始化 -

int a = 5;

int main()
{
    int c = a; // local or automatic variable initialized by a non 
    constant variable
}

但外部也称为全局变量和静态变量不能用非常量变量初始化。

int a = 3
int b = a // cannot be initialized by non constant variable

int main()
{
static int d;
d = a // cannot be initialized by a non constant variable
}

它还指出,每当它们所在的代码块由编译器运行时,自动或局部变量都会重新初始化。因为每次进入代码块时,编译器都会自动分配和释放变量的内存位置。

void abc(void);// function parameter

int main()
{
   abc();
   abc();
}
void abc()
{
  int i = 0;// automatic variable i is re-intialized every time abc is called
  static x = 0; //static variable retains its value
  i ++ ;
  x ++;
  printf("%d\n",i );
  printf("%d\n",x );
}

输出 - 1 1 1 2

相关问题