Questions 1–6
Answer first yourself, only then open the answer. The code was compiled with the course flags.
1. What happens when main.c is compiled?
daytime.h (without an #ifndef guard):
typedef struct {
int hour;
int min;
} Daytime;
lecture.h includes daytime.h, and main.c includes both:
#include "daytime.h"
#include "lecture.h"
Answer
The error conflicting types for 'Daytime': daytime.h gets into the same main.c twice, and Daytime is defined twice. That's why every .h is wrapped in #ifndef DAYTIME_H / #define DAYTIME_H / #endif. (Topic 7)
2. Why doesn't the program link?
daytime.c:
static int nearly_equal(double a, double b) {
return a - b < 0.001 && b - a < 0.001;
}
main.c has int nearly_equal(double a, double b); and calls nearly_equal(1.0, 2.0).
Answer
The linker: undefined reference to `nearly_equal'. A static function is visible only in its own file – it is the module's internal helper. If it's needed elsewhere, remove static and declare it in the .h file. (Topic 7)
3. What does it print (on a 64-bit computer)?
int a[10] = {0};
int *p = a;
printf("%zu %zu\n", sizeof a, sizeof p);
Answer
40 8
sizeof a is the size of the whole array: 10 × 4 bytes. sizeof p is the size of a pointer: an address takes 8 bytes, however many elements are behind it. (Topic 8)
4. What does it print?
void swap(int a, int b) {
int t = a;
a = b;
b = t;
}
int main(void) {
int x = 1, y = 2;
swap(x, y);
printf("%d %d\n", x, y);
return 0;
}
Answer
1 2
The function gets copies of x and y and swaps those. For x and y themselves to change: void swap(int *a, int *b) with *a, *b inside and the call swap(&x, &y). (Topic 8)
5. What does it print?
unsigned int a = 6, b = 3;
printf("%u %u %u %u\n", a & b, a | b, a ^ b, a << 2);
Answer
2 7 5 24
6 = 110, 3 = 011. & – 1 where both are 1: 010 = 2. | – where at least one is: 111 = 7. ^ – where exactly one is: 101 = 5. << 2 – × 2 twice: 24. (Topic 8)
6. Why doesn't this code compile?
char name[20] = "Ona";
if (name == "Ona") {
printf("hello, Ona\n");
}
Answer
== compares addresses, not letters: the address of the array name and the address of the literal "Ona". GCC: comparison with string literal results in unspecified behavior, and -Werror turns it into an error. Strings are compared with strcmp(name, "Ona") == 0. (Topic 9)