Consider the following code running on an embedded system. What will be printed?
#include <stdio.h> volatile int flag = 0; void interrupt_handler() { flag = 1; } int main() { while (!flag) { // wait for interrupt } printf("Flag set!\n"); return 0; }
Think about the role of volatile in embedded systems.
The volatile keyword tells the compiler that flag can change unexpectedly (e.g., by an interrupt). Without volatile, the compiler might optimize the loop to an infinite loop. Here, flag is volatile, so the loop exits when flag is set by the interrupt.
What will be printed by this embedded C code?
#include <stdio.h> int main() { char buffer[5] = {1, 2, 3, 4, 5}; char *p = buffer; printf("%d\n", *(p + 3)); return 0; }
Remember that pointer arithmetic moves by element size.
The pointer p points to buffer[0]. Adding 3 moves it to buffer[3], which contains the value 4.
Analyze the following embedded C code. What error will it cause when run?
#include <stdio.h> int main() { int *ptr = NULL; *ptr = 10; printf("%d\n", *ptr); return 0; }
Think about what happens when you write to a null pointer.
Dereferencing a NULL pointer causes a segmentation fault (crash) because it points to an invalid memory location.
Which of the following code snippets will cause a syntax error in embedded C?
Look for missing semicolons.
Option A is missing a semicolon after int x = 10, causing a syntax error.
Given the following struct on a 32-bit embedded system, how many bytes does it occupy?
struct Data {
char a;
int b;
char c;
};Consider padding and alignment on a 32-bit system.
On a 32-bit system, int requires 4-byte alignment. The struct layout is:
- a: 1 byte
- 3 bytes padding
- b: 4 bytes
- c: 1 byte
- 3 bytes padding
Total: 12 bytes.