旧事之局部变量和全局变量
2010-07-20 16:49
218 查看
局部变量和全局变量
局部变量可以和全局变量重名,并且会覆盖全局变量。在引用全局变量时,有两种方式可以选择:引用头文件的方式和extern关键字。
程序的局部变量存放在堆栈
当中,全局变量存放在静态区
中,动态申请数据存放在堆
中。
下面看一个具体的列子:
运行结果:
121212121212121212
waiting for thread to finished...
joined,it returned OK!
局部变量可以和全局变量重名,并且会覆盖全局变量。在引用全局变量时,有两种方式可以选择:引用头文件的方式和extern关键字。
程序的局部变量存放在堆栈
当中,全局变量存放在静态区
中,动态申请数据存放在堆
中。
下面看一个具体的列子:
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <pthread.h> int run_now = 1; void *thread_fun(void *arg); int main() { pthread_t a_thread; void *thread_result=NULL; int print_count1 = 0; //int run_now = 1; /*这里就是局部变量,如果这句不注释的话,程序运行的结果: 1 waiting for thread to finished... joined,it returned OK! */ if(pthread_create(&a_thread,NULL,thread_fun,&run_now)!=0) { perror("thread create failed"); exit (1); } while(print_count1++ < 20) { if(run_now == 1) { printf("1"); run_now = 2; } else sleep(1); } puts("/nwaiting for thread to finished.../n"); if(pthread_join(a_thread,&thread_result)) { perror("thread join failed"); exit (1); } printf("joined,it returned %s/n",(char *)thread_result); return 0; } void *thread_fun(void *arg) { int print_count2 = 0; while(print_count2++ < 20) { if(run_now == 2) { printf("2"); run_now = 1; } else sleep(1); } pthread_exit("OK!"); }
运行结果:
121212121212121212
waiting for thread to finished...
joined,it returned OK!
相关文章推荐
- C语言中局部变量和全局变量解释
- 全局与局部变量及递归
- C/C++中的静态全局变量,静态局部变量,全局变量,局部变量的区别
- javascript学习笔记(二):定义函数、调用函数、参数、返回值、局部和全局变量
- 关于局部变量、静态局部变量、全局变量、静态全局变量
- 局部变量和全局变量
- php部分(查看文件、建立站点、语法变量、变量的几个方法、“全局局部变量的调用”、static、函数参数的作用域);
- 正确得到线程退出信息的方法详解-变量存储退出信息结构、使用动态存储的方式退出信息结构、使用全局变量方式推相互信息结构、使用main函数中的局部变量存储退出信息结构
- C++ 全局变量、静态全局变量和静态局部变量的异同
- Js全局变量与局部变量_this关键字
- 全局变量与局部变量
- 深入浅出理解局部、全局、静态、动态、外部变量
- 【Xcode学C-5】结构体、全局局部变量以及枚举变量的知识点
- C++中局部变量、全局变量、静态局部变量、静态全局变量
- C|C++中的静态全局变量,静态局部变量,全局变量,局部变量的区别
- js全局变量与局部变量 预解析与作用域链详解
- 变量的6种作用:全局作用域,文件作用域,命名空间作用域,类作用域,局部作用域,语句作用域
- 全局变量、静态全局变量、静态局部变量和局部变量
- static全局(局部)变量与普通的全局(局部)变量的区别
- vs2008如何新建自己工程的环境变量(局部)和 Windows系统(全局).