C Pitfalls – Test yourself (what will be printed)

C is a great programming language , very fast , almost low level but its because the responsibility to write a good working code (and secure) is the developer.

Array access , type casts, function parameters and more are not checked by the runtime so if you do something wrong – you crash

It is important for any C developer to be familiar with some pitfalls. Let see some , try to think what will be printed and check the answers bellow

Note: There is no compilation errors in all the following pitfalls

Pitfall 1

typedef struct {
	int a;
	int b;
}T1;

int main(void)
{
 int a=90,res;
 T1 m = {10,20};
 T1 *p = &m;
 res = p-->a;

 printf("res=%d\n",res);
 return 0;
}

Check Answer

Pitfall 2

int main(void)
{
 int x=10;

 if(x > 30,400)
	printf("yes\n");
 else
	printf("no\n");

 x=100;

 if(x > 30,400)
	printf("yes\n");
 else
	printf("no\n");


 return 0;
}

Check Answer

Pitfall 3

int main(void)
{
 int x=100,y=20,res;
 int *p,p1;
 int *q;
 p=&x;
 q=&y;
 p1=p;

 res = *p/*q;

 /* redirect access  */
 *p1++;
 printf("res=%d\n",res);


 return 0;
}

Check Answer

Pitfall 4

int main(void)
{
 int x=10,y=20,res;

 res=x---y;

 printf("res=%d x=%d y=%d\n",res,x,y);


 return 0;
}

Check Answer

Pitfall 5

int main(void)
{
 int f=0x2; // 0010
 int x=0x8; // 1000
 int r1,r2;
 if(x | f != 10)
	printf("yes\n");
 else
	printf("no\n");

 r1 = x * 8 + 1;
 r2 = x << 3 + 1;

 if(r1==r2)
	printf("yes\n");
 else
	printf("no\n");


 return 0;
} 

Check Answer

Pitfall 6

int main(void)
{
 int x=10,y=20,res;

 switch(x)
 {
 	case 2:
		 y=10;  
		 break;    
	case 4:
		 y=33;
		 break;
	case 6:
		 y=44;
		 break;
	case 8:
		 y=55;
		 break;
	defualt:
		 y=100;	
		 break;
 } 
printf("y=%d\n",y);

 return 0;
}

Check Answer

Pitfall 7

int fn(int x, unsigned int factor) {
	return x / factor;
}


int main(void)
{
 int x=-20,y=10,res;

 res = fn(x,y);
 printf("y=%d\n",res);

 return 0;
}

Check Answer

who got 7/7 ?

 

Tagged ,

2 thoughts on “C Pitfalls – Test yourself (what will be printed)

  1. Devlish – but great fun to solve.

  2. Yes, I did 7/7… Use vim, it has both syntax coloring and vi compatibility, and it runs on Linux and Windows, and is useful to know when you work with a bare-bones Linux

Comments are closed.