Drills
Drills: check yourself
Answer on your own first, and only then open the answer.
1. What does it print?
int x = 4;
int *p = &x;
*p += 3;
printf("%d\n", x);
Answer
7
*p is x, so *p += 3 increases x.
2. What does it print?
printf("%u %u %u\n", 12u & 10u, 12u | 1u, 1u << 4);
Answer
8 13 16
1100 & 1010 = 1000 (8); 1100 | 0001 = 1101 (13); 1 << 4 = 2⁴ = 16.
3. Why doesn't a change, and how do you fix it?
void double_it(int x) {
x = x * 2;
}
int a = 5;
double_it(a);
Answer
The function gets a copy of a and doubles the copy. It needs a pointer:
void double_it(int *x) {
*x = *x * 2;
}
double_it(&a);
4. What is the type of q?
int *p, q;
Answer
int. The star belongs only to p, which is why you write one declaration per line.
5. What does it print?
int t[] = {1, 2, 3, 4};
int *q = t + 1;
printf("%d %d\n", *q, q[2]);
Answer
2 4
q points to t[1], so *q is 2, and q[2] is two boxes further on, t[3] = 4.