C语言函数体内,无条件的大括号的作用
这有两个程序:
程序①:
- C/C++ code
#include<stdio.h>main(){ int b=4; { b=7; printf("b=%d",b); } printf("b=%d\n",b);}输出为b=7, b=7;
程序②:
- C/C++ code
main(){ int b = 2; { int b = 1; printf("b=%d" ,b); // 输出1 } // int a = 2; // 错误 printf("b=%d", b); // 输出2 return 0;}输出为:b=1,b=2请问为什么会不一样呢??这个函数体内没有条件的大括号{}有什么作用吗?
[解决办法]
在花括号内,如果变量前面带类型,则相当于新创建一个变量,作用域只在花括号内;
变量前面不带类型,会屏蔽掉外层代码块名字相同的变量;
gcc中是这样的:
- C/C++ code
[root@bogon temp]# cat t1.c#include <stdlib.h>#include <string.h>#include <stdio.h>int main(){ int b = 2; { b = 1; printf("b=%d " ,b); // } printf("b=%d ", b); // putchar('\n'); int c = 2; { int c = 1; printf("c=%d " ,c); // } printf("c=%d ", c); // putchar('\n');}[root@bogon temp]# ./t1b=1 b=1 c=1 c=2 [root@bogon temp]#
[解决办法]
{
}
直接看成
if(1)
{
}
就行。
[解决办法]