在C语言中,switch
语句用于执行多个条件并基于这些条件执行不同的动作。switch
语句本身并不直接支持返回值,如果你想在switch
语句中返回一个值,你需要将这个值存储在一个变量中,然后在switch
语句之后返回这个变量。
以下是一个简单的例子:
#include <stdio.h> int test(int x) { int result; switch (x) { case 1: result = 10; break; case 2: result = 20; break; default: result = 0; } return result; } int main() { printf("%dn", test(1)); // 输出:10 printf("%dn", test(2)); // 输出:20 printf("%dn", test(3)); // 输出:0 return 0; }
在这个例子中,我们定义了一个函数test
,它接受一个整数参数x
,我们在switch
语句中根据x
的值来设置result
的值,我们返回result
的值。