#include <stdio.h>
int main() {
int a = 3;
int b = 4;
int c = 5;
int result = a + b * c; // 乘法优先级高于加法
printf("result = %d\n", result); // 输出: result = 23 (4 * 5 = 20, 3 + 20 = 23)
return 0;
}
解释:
在a + b * c中,乘法操作b * c的优先级高于加法操作a + b,因此先计算b * c = 20,然后再进行加法运算3 + 20 = 23。
#include <stdio.h>
int main() {
int a = 10, b = 20;
a = a ^ b; // a = 10 ^ 20
b = a ^ b; // b = (10 ^ 20) ^ 20
a = a ^ b; // a = (10 ^ 20) ^ 10
printf("a = %d, b = %d\n", a, b); // 输出: a = 20, b = 10
return 0;
}
解释:
使用^(异或操作符),通过一系列的异或操作,我们可以交换两个数的值。第一步是a = a ^ b,接着通过再次异或将原本的a和b值互换。
这个技巧避免了使用临时变量。
7. 整型提升与算术转换
C语言中的整型提升是指小类型(如char、short)会在进行算术运算时被自动转换为int类型。
整型提升示例
复制代码
#include <stdio.h>
int main() {
char a = 5;
short b = 10;
int result = a + b; // a 和 b 会提升为 int 类型进行加法
printf("result = %d\n", result); // 输出: result = 15
return 0;
}
#include <stdio.h>
int main() {
float a = 3.14;
int b = 2;
float result = a + b; // b 会被转换为 float 类型
printf("result = %.2f\n", result); // 输出: result = 5.14
return 0;
}