C语言switch分支case调用函数
时间: 2023-11-21 15:52:46 浏览: 200
在C语言中,我们可以在switch分支中调用函数。在case后面跟上函数名即可调用该函数。需要注意的是,函数必须在调用之前进行声明或定义,否则编译器会报错。下面是一个示例代码:
```
#include <stdio.h>
void function1(int x, int y) {
printf("x + y = %d\n", x + y);
}
void function2(int x, int y) {
printf("x * y = %d\n", x * y);
}
int main() {
char ch;
int a = 17, b = 20;
printf("请输入操作类型(A或B):");
scanf("%c", &ch);
switch(ch) {
case 'A':
case 'a':
function1(a, b);
break;
case 'B':
case 'b':
function2(a, b);
break;
default:
printf("无效操作类型!\n");
break;
}
return 0;
}
```
在上面的代码中,我们定义了两个函数function1和function2,分别用于执行加法和乘法操作。在main函数中,我们通过switch语句根据用户输入的操作类型调用相应的函数。需要注意的是,我们在调用函数之前进行了函数声明,这样编译器就能够正确地识别函数。
阅读全文
相关推荐


















