Embedded C Programming: Loops, Arrays, and goto
1. Loop Control
C provides multiple loop constructs for executing code repeatedly. Common loops include while, do...while, for, and unconditional loops using goto.
1.1 While Loop
int i = 0; // Initialization
while (i < 10) {
printf("i = %d\n", i);
i++; // Increment to eventually terminate the loop
}
- The condition
expr1is checked first; if true, the loop body executes. i++gradually makes the condition false, ending the loop.- Suitable for count-controlled loops.
1.2 Do…While Loop
int i = 0;
do {
printf("i = %d\n", i);
i++;
} while (i < 10);
- Executes the loop body before checking the condition.
- Ensures the loop body runs at least once.
1.3 Infinite Loop
while (1) {
// Infinite loop body
}
- Commonly used in embedded systems for main loops or tasks.
- Make sure to include proper exit conditions or interrupts.
2. Unconditional Jump with goto
goto allows unconditional jumps to a specified label, but it is not recommended in application-level code.
Example
int i = 0;
loop:
if (i < 10) {
printf("i is %d\n", i);
i++;
goto loop;
}
loop:defines the jump label.gotois often used in Linux kernel programming or for error handling.- For general applications, prefer
fororwhileloops instead.
3. Nested Loops
Nested loops are commonly used in embedded systems for matrix operations or 2D array traversal, for example, printing a multiplication table:
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
printf("%d*%d=%d ", i, j, i*j);
}
printf("\n");
}
- Outer loop runs once per iteration.
- Inner loop executes multiple times.
- Use
continueto skip the current iteration orbreakto exit the loop.
4. Loop Control Statements
continue;→ skips the rest of the current iteration, moving to the next.break;→ immediately exits the loop.
Example
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (j == 3) continue; // Skip j=3
if (i == 2) break; // Exit inner loop when i=2
printf("%d,%d\n", i, j);
}
}
5. Function Recursion
- Recursion is sometimes used in embedded programming.
- Be mindful of stack limitations, as deep recursion may cause stack overflow.
6. Array Basics
An array is a finite collection of elements of the same type, widely used in embedded systems for data buffering and signal processing.
6.1 Defining Arrays
int a[5]; // Define an integer array of length 5
int b[2+4]; // Expressions can also be used for size
- Array elements are stored consecutively in memory.
- Indexing starts at 0, with the maximum index
N-1.
6.2 Accessing Elements
a[0] = 10; // First element
a[1] = 20; // Second element
printf("%d\n", a[2]); // Third element
- Array indices can be variables, constants, or expressions.
- Arrays cannot be operated on as a whole, only individual elements.
- Avoid out-of-bounds access to prevent undefined behavior.



1130

被折叠的 条评论
为什么被折叠?



