C语言语句是C程序中的基本构建块,它们用于执行特定的任务。C语言中的语句可以分为几类,包括:
- 表达式语句:表达式语句是由一个表达式后面跟着分号组成的语句。它用于执行计算并产生结果。例如:
x = y + z;
- 复合语句(代码块):复合语句是由一对花括号
{}
包围起来的多条语句。它们允许在程序中组织多条语句并作为一个单元执行。例如:
{
int a = 5;
int b = 3;
int sum = a + b;
}
- 选择语句:选择语句用于根据条件选择要执行的代码块。常见的选择语句包括
if
语句和switch
语句。例如:
if (x > y) {
printf("x is greater than y");
} else {
printf("y is greater than or equal to x");
}
switch (choice) {
case 1:
printf("You chose option 1");
break;
case 2:
printf("You chose option 2");
break;
default:
printf("Invalid choice");
}
- 迭代语句:迭代语句用于重复执行一段代码,直到满足某个条件。常见的迭代语句包括
for
循环、while
循环和do-while
循环。例如:
for (int i = 0; i < 5; i++) {
printf("%d ", i);
}
int i = 0;
while (i < 5) {
printf("%d ", i);
i++;
}
int i = 0;
do {
printf("%d ", i);
i++;
} while (i < 5);
- 跳转语句:跳转语句用于改变程序的执行顺序。常见的跳转语句包括
break
、continue
和return
。例如:
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // 跳出循环
}
printf("%d ", i);
}
for (int i = 0; i < 10; i++) {
if (i == 5) {
continue; // 跳过本次循环
}
printf("%d ", i);
}
int add(int x, int y) {
return x + y; // 返回函数值并结束函数执行
}
这些是C语言中常见的语句类型,它们可以组合使用以构建复杂的程序逻辑。