码迷,mamicode.com
首页 > 编程语言 > 详细

C++_知识点_全局变量

时间:2015-11-03 22:28:37      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:

全局变量

  -全局变量即在函数之外定义的变量

  -全局变量保存在静态存储区

 

注意:

  -全局变量只能声明和初始化

  -全局变量不能进行运算、赋值(非初始化)、调用函数

    -否则会出现编译错误

      -error: expected constructor, destructor, or type conversion before ‘.‘ token

      -initializer element is not constant

eg:

  

#include <stdio.h>  
int a = 1;  
int b = 2;  
int c = a+b;// error 不能运算  

int main() {  
    printf("c is %d\n", c);  
    return 0;  
}  
#include <stdio.h>

int a = 0;

a = 1; // error 不能赋值

int main(){

  return 0;          
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

srand((unsigned int)time(NULL)); // error 不能调用函数

int sum = add(); // error 不能调用函数

int add(){
  return 1;  
}

int main(){
  return 0;  
}
#include <iostream>

using namespace std;

const int b = 8;

int a = b; // sucess 

int main(){

    return 0;
}
#include <iostream>

using namespace std;

const int b = 8;

const int add(){
    return 1;
}

int a = add(); // success

int main(){

    return 0;
}
#include <iostream>

using namespace std;

const int b = 8;

int a;

a = 1; // error ??

int main(){

    return 0;
}

 

 

总结:

  -全局变量保存在静态存储区,其值必须在编译时确定,不能在执行时确定

  -所以定义一个全局变量时必须使用常量

 

C++_知识点_全局变量

标签:

原文地址:http://www.cnblogs.com/Neo-Lc/p/4934446.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!