嵌入式C语言基础试题


#include <stdio.h>

//设置a值的bit3位,使其他bit位保持不变
#define SETBIT3(a)	((a) |= (1<<3))
#define RESETBIT3(a)	((a) &= ~(1<<3))

//测试函数声明
void test1(void);
void test2(void);
void test3(void);
void test4(void);
void test5(void);
void test6(void);
void test7(void);
void test8(void);


//声明函数指针结构体
typedef struct myTest
{
	void (*test1)(void);
	void (*test2)(void);
	void (*test3)(void);
	void (*test4)(void);
	void (*test5)(void);
	void (*test6)(void);
	void (*test7)(void);
	void (*test8)(void);

}mytest;

mytest myTEST;

mytest* test(void)
{
	myTEST.test1 = test1;
	myTEST.test2 = test2;
	myTEST.test3 = test3;
	myTEST.test4 = test4;
	myTEST.test5 = test5;
	myTEST.test6 = test6;
	myTEST.test7 = test7;
	myTEST.test8 = test8;

	return &myTEST;
}

mytest *testFunc = NULL;

void test1(void)
{
	printf("result:0x%02x\n",(char)(((int)(0x52b89a))&0xaae7));
	//result=0xffffff82
}

void test2(void)
{
	int a[3]={1,3,5};
	int *p,*q;
	p=a;
	q=&a[2];
	printf("result:%d\n",a[q-p]);
	//result=5 理解为角标加减,q=2 p=0,则应该打印a[2-0]=a[2]的值
}

#define MIN(x,y) ((x)<(y))?(x):(y)
void test3(void)
{
	int a=1,b=2;
	printf("result=%d\n",MIN(a++,b));//运行结果result=2
	printf("a=%d\n",a);//运行结果a=3
	//宏为预处理,先替换格式再进行运算实际是打印如下内容
	//(a++)<b?(a++):b,a++是先应用再自增,1<2,理应打印a的值,
	//但是a在进行条件判断后自增了,这时a的值为2,执行完整条语句,
	//a最终值为3
}

void test4(void)
{
	//错误字符常量定义
	//char ch1="f"(实际为"f\n"),ch2=x(x未定义)
	//正确的字符常量如下
	//65为'A'的十进制,'\xab'=0xab
	char ch3=65,ch4='\xab';
	printf("%c %d\n",ch3,ch4);
}

void test5(void)
{
	int i=0;
	while(i++<5);
	printf("i=%d\n",i);//i=6
	//结果i=6,i=5时,跳出循环,后i自增,再打印即为6
}

void test6(void)
{
	int y=100;
	while(y--);
	printf("y=%d\n",y);//y=-1
}

void test7(void)
{
	int x;
	float y = 5.5;
	//y是单精度浮点数,强制转换为int类型,计算机不会进行四舍五入,这个过程叫数据截断
	printf("y = %d\n",(int)y);//y = 5;
	x = (float)(y*3+((int)y%4));
	//运算过程(float)(5.5*3+((int)5.5)%4)
	//(float)(16.5+5%4)=(float)(17.5)
	//由于x是int类型的,结果赋值给int类型后,x值被截断,最终结果17
	printf("x = %d\n",x);
}

void test8(void)
{
	int a = 0;
	SETBIT3(a);
	printf("after set bit 3 a=%d\n",a);

	a = 0xff;
	RESETBIT3(a);
	printf("after reset bit 3 a=%d\n",a);
}

//计算一个值的平方
long square(volatile int *ptr)
{
	int a;
	a = *ptr;
	return a*a;
}

int main(int argc, char *argv[])
{	
	int a=5;
        void (*ptest[8])(void) = {test1,test2,test3,test4,test5,test6,test7,test8};
	

        testFunc = test();
        testFunc->test1();//函数指针结构体调用函数
        
	if(testFunc == NULL)
	{
		printf("init err\n");
		return -1;
	}

	if(argc < 2)
	{
		printf("please input test num with run ./a.out 1~7");
		return -1;
	}
	
        //函数指针数组,实现函数调用
	ptest[atoi(argv[1])]();

        //计算a值的平方并赋值给a
	a = square(&a);
	printf("square = %d\n",a);
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_28643619/article/details/88350213