{ }包围起来的代码。代码块在C语言中随处可见,例如函数体、选择结构、循环结构等。不包含代码块的C语言程序根本不能运行,即使最简单的C语言程序(上节已经进行了展示)也要包含代码块。
#include <stdio.h>
//函数声明
int gcd(int a, int b); //也可以写作 int gcd(int, int);
int main(){
printf("The greatest common divisor is %d\n", gcd(100, 60));
return 0;
}
//函数定义
int gcd(int a, int b){
//若a<b,那么交换两变量的值
if(a < b){
int temp1 = a; //块级变量
a = b;
b = temp1;
}
//求最大公约数
while(b!=0){
int temp2 = b; //块级变量
b = a % b;
a = temp2;
}
return a;
}
运行结果:
#include <stdio.h>
int sum(int m, int n);
int main(){
printf("The sum from 1 to 100 is %d\n", sum(1, 100));
return 0;
}
int sum(int m, int n){
int sum = 0;
for(int i=m; i<=n; i++){ //i是块级变量
sum += i;
}
return sum;
}
变量 i 定义在循环条件里面,所以是一个块级变量,它的作用域就是当前 for 循环,出了 for 循环就无效了。
#include <stdio.h>
#include <string.h>
int strchar(char *str, char c);
int main(){
char url[] = "http://c.biancheng.net";
char letter = 'c';
if(strchar(url, letter) >= 0){
printf("The letter is in the string.\n");
}else{
printf("The letter is not in the string.\n");
}
return 0;
}
int strchar(char *str, char c){
for(int i=0,len=strlen(str); i<len; i++){ //i和len都是块级变量
if(str[i] == c){
return i;
}
}
return -1;
}
循环条件里面可以定义一个或者多个变量,这段代码我们就定义了两个变量,分别是 i 和 len,它们都是块级变量,作用域都是当前 for 循环。
#include <stdio.h>
int main(){
int n = 22; //编号①
//由{ }包围的代码块
{
int n = 40; //编号②
printf("block n: %d\n", n);
}
printf("main n: %d\n", n);
return 0;
}
运行结果:
#include <stdio.h>
int m = 13;
int n = 10;
void func1(){
int n = 20;
{
int n = 822;
printf("block1 n: %d\n", n);
}
printf("func1 n: %d\n", n);
}
void func2(int n){
for(int i=0; i<10; i++){
if(i % 5 == 0){
printf("if m: %d\n", m);
}else{
int n = i % 4;
if(n<2 && n>0){
printf("else m: %d\n", m);
}
}
}
printf("func2 n: %d\n", n);
}
void func3(){
printf("func3 n: %d\n", n);
}
int main(){
int n = 30;
func1();
func2(n);
func3();
printf("main n: %d\n", n);
return 0;
}
下图展示了这段代码的作用域:
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有