1. 写函数判断大端还是小端
https://baike.baidu.com/item/%E5%A4%A7%E5%B0%8F%E7%AB%AF%E6%A8%A1%E5%BC%8F/6750542?fr=aladdin
#include <stdio.h>
int main()
{
short x = 0x0102;
char x0 = ((char *)&x)[0];
char x1 = ((char *)&x)[1];
printf("(char *)&x\t\t= %d, x0 = 0x%x\n", (char *)&x, x0);
printf("((char *)&x)+1\t= %d, x1 = 0x%x\n", ((char *)&x)+1, x1);
if (x0 == 0x01) {
printf("低地址存高字节--大端\n");
} else if (x0 == 0x02) {
printf("低地址存低字节--小端\n");
}
return 0;
}
2. 用宏定义实现swap
另外:do {...} while (0) 在宏定义中的作用:使用do{...}while(0)构造后的宏定义不会受到大括号、分号等的影响,总是会按你期望的方式调用运行。
详细参见:https://www.cnblogs.com/lanxuezaipiao/p/3535626.html
#include <stdio.h>
#define SWAP1(x,y) do {\
int tmp = x;\
x = y;\
y = tmp;} while(0)
#define SWAP2(x,y) do {\
x = x + y;\
y = x - y;\
x = x - y;} while(0)
// 注意while(0)后不要添加分号,实际展开时可能导致编译错误,如下示例if-else不带大括号时会导致编译错误
int main()
{
int i = 1, j = 2;
printf("before: i = %d, j= %d\n", i, j);
SWAP1(i, j);
printf("SWAP1: i = %d, j= %d\n", i, j);
SWAP2(i, j);
printf("SWAP2: i = %d, j= %d\n", i, j);
if (i==2)
SWAP2(i,j);
else
printf("this is else\n");
return 0;
}
9行添加分号后编译错误: -- 展开后在调用处比预期多一个分号,导致if语句结束
3. 用宏定义求数组的元素个数
#include <stdio.h>
#define ARR1_LEN(arr) (sizeof(arr)/sizeof(arr[0]))
#define ARR2_LEN(arr) (sizeof(arr)/sizeof(arr[0][0]))
int main()
{
int arr1[4];
char arr2[3][2];
printf("sizeof(arr1) = %d\n", sizeof(arr1));
printf("sizeof(arr1[0]) = %d\n", sizeof(arr1[0]));
printf("LEN(arr1)=%d\n", ARR1_LEN(arr1));
printf("sizeof(arr2) = %d\n", sizeof(arr2));
printf("sizeof(arr2[0]) = %d, sizeof(arr2[0][0]) = %d\n", sizeof(arr2[0]), sizeof(arr2[0][0]));
printf("LEN(arr2)=%d\n", ARR2_LEN(arr2));
return 0;
}
注意结果中sizeof计算与实际数组元素个数的关系
4. 内联函数
分析:https://blog.csdn.net/Hxj_CSDN/article/details/80919091
截取上述文中结论,如果函数B满足以下2个条件,就可以考虑把它设计为内联函数:
(1)函数的代码简短: 简短到其执行时间和切换时间具有可比性,比如内部只有3-4条语句。因为如果函数复杂,函数体执行时间较长,那么节约函数的切换时间显得非常可笑,并且此时大量的代码被重复拷贝,更加得不偿失。
(2)函数被频繁调用: 如果一个函数的使用率很低,那么对它的优一切化都是徒劳的,在大型项目中,真正需要优化的都是热点代码,能够明显显示程序运行效率的代码
内联与宏实现:https://blog.csdn.net/u014376961/article/details/87989356
另一个例子如:https://blog.csdn.net/cpongo3/article/details/93996094
5. int类型变量:整数与小数运算
#include <stdio.h>
int main()
{
int x = 3;
x = 3 + 1.78;
printf("x=%d, x=%f\n", x, x);
return 0;
}
6.一行代码有必要写成一个函数吗?
https://www.zhihu.com/question/413568343
引用:https://www.zhihu.com/question/413568343/answer/1401707130
看这行代码有多大的意义,如果你这行代码有很多地方在用,并且将来有可能会改变行为,那这一行代码就有抽成一个函数的必要。要明白函数的意义,函数是为了描述一个行为,而且也为了复用,所以针对这两点就可以判断出你的这一行代码有没有必要写成一个函数。
7.关于表达式与printf打印
#include <stdio.h>
void print(void)
{
int a;
int b = a = 1;
int c=3;
printf("关于表达式的值与printf打印:\n");
printf("a=%d,b=%d,c=%d\n", a, b, c);
printf("a=%d, b=%d, (c=2):%d, (c=b):%d, c=%d\n", (a=c), b, (c=2), (c=b), c);
printf("(c=2):%d\n", (c=2));
printf("(c=b):%d\n", (c=b));
printf("a=%d,b=%d,c=%d\n\n", a, b, c);
}
void expression(void)
{
int a;
a = 123,456; // 两个表达式被逗号连接成了一个表达式;最左边的表达式最先求值
printf("关于逗号运算符:\n");
printf("a=%d\n", a);
a = (789,10); // 整个逗号表达式的值是逗号右侧表达式的值
printf("a=%d\n", a);
}
int main()
{
print();
expression();
return 0;
}



京公网安备 11010502036488号