关于C语言中变量作用域的个人心得

    这是本人的第一篇博客,内容简单总结浅陋。但这会是我写博客的开始,好啦!废话不多说。。。。

    学过C语言的同学可能都知道,在C中变量都具有作用域的说法。以下是标准的解释和案例:


    以上内容不难理解,一个函数的花括号为一个块。若一个函数带有形参,虽然函数的形参的声明在函数的左花括号之前,但是他们也具有块作用域,属于函数这个块。因此,在上述实例代码中变量 cleo和patrick都具有相同的块作用域。那么,在for while 这种循环语句块中,变量的作用域又是咋样的?

    以下是教科书般的解释:





对于上述的例子我自己写了一段代码来实现:


#include <stdio.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char** argv) {
	
	int i=2;
//	int j=0;
	for(int j=0;j++;j<3){
		printf("j=%d\n",j);
	}
	printf("///////////////////////////////////"); //实现分割
	printf("\ni=%d\tj=%d",i,j);
	return 0;
}

设计这段代码本意是看看能不能在for语句块以外输出j。然而,编译都没通过。以下是错误信息:


[Error]name lookup of 'j' changed for OSI 'for' scoping  大致意思是  查找name为j的变量超出了OSI的‘for’的范围。

嗯~~,所以我又小小的改变了一下我的代码:

#include <stdio.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char** argv) {
	
	int i=2;
	int j=0;
	for(j;j++;j<3){
		printf("j=%d\n",j);
	}
	printf("///////////////////////////////////");
	printf("\ni=%d\tj=%d",i,j);
	return 0;
}

编译和运行一下:



能运行成功!!但是好像没打印出for语句块内的printf语句,嗯~这个问题留在下次。但是问题看来还真是作用域的问题。

好啦!!!


















猜你喜欢

转载自blog.csdn.net/qq_36171263/article/details/80831073