C语言 第三课 变量

C 中的变量声明

变量声明向编译器保证变量以指定的类型和名称存在,这样编译器在不需要知道变量完整细节的情况下也能继续进一步的编译。

变量声明只在编译时有它的意义,在程序连接时编译器需要实际的变量声明。

变量的声明有两种情况:

  • 1、一种是需要建立存储空间的。例如:int a 在声明的时候就已经建立了存储空间。
  • 2、另一种是不需要建立存储空间的,通过使用extern关键字声明变量名而不定义它。 例如:extern int a 其中变量 a 可以在别的文件中定义的。
  • 除非有extern关键字,否则都是变量的定义。
extern int i; //声明,不是定义
int i; //声明,也是定义

实例

尝试下面的实例,其中,变量在头部就已经被声明,但是定义与初始化在主函数内:

实例

#include <stdio.h>
 
// 变量声明
extern int a, b;
extern int c;
extern float f;
 
int main ()
{
  /* 变量定义 */
  int a, b;
  int c;
  float f;
 
  /* 初始化 */
  a = 10;
  b = 20;
  
  c = a + b;
  printf("value of c : %d \n", c);
 
  f = 70.0/3.0;
  printf("value of f : %f \n", f);
 
  return 0;
}

当上面的代码被编译和执行时,它会产生下列结果:

value of c : 30
value of f : 23.333334



const 关键字

您可以使用 const 前缀声明指定类型的常量,如下所示:

const type variable = value;

具体请看下面的实例:

实例

#include <stdio.h>
 
int main()
{
   const int  LENGTH = 10;
   const int  WIDTH  = 5;
   const char NEWLINE = '\n';
   int area;  
   
   area = LENGTH * WIDTH;
   printf("value of area : %d", area);
   printf("%c", NEWLINE);
 
   return 0;
}

 

当上面的代码被编译和执行时,它会产生下列结果:
value of area : 50
 
posted @ 2018-01-03 16:47  Justice-V  阅读(106)  评论(0)    收藏  举报