Types, Functions, and Control Flow in C
C makes representation harder to ignore
Section titled “C makes representation harder to ignore”#include <stdio.h>
int sum_to(int limit) { int total = 0; for (int value = 1; value <= limit; value++) { total += value; } return total;}
int main(void) { printf("%d\n", sum_to(5)); return 0;}Compile with warnings and trace value and total for every iteration. C requires declared types and does not protect every operation from overflow or invalid conversion.
Validate command-line shape first
Section titled “Validate command-line shape first”#include <errno.h>#include <stdio.h>#include <stdlib.h>
int main(int argc, char **argv) { if (argc != 2) { fprintf(stderr, "usage: %s number\n", argv[0]); return 2; }
char *end = NULL; errno = 0; long value = strtol(argv[1], &end, 10); if (errno != 0 || end == argv[1] || *end != '\0') { fprintf(stderr, "invalid integer\n"); return 3; }
printf("value=%ld\n", value); return 0;}argc counts arguments including the program name. argv contains pointers to their strings. strtol reports where parsing stopped, allowing the program to reject 12oops instead of silently accepting 12.
Test no argument, 12, 12oops, and a very large number. After each run, print $? to record the exit status.
Knowledge check
Question 1 of 2
Knowledge check complete
You answered all 2 questions correctly.
What this gives us as researchers
Section titled “What this gives us as researchers”You can trace explicit C values and identify validation assumptions around arguments and conversion. Next we add arrays, strings, addresses, and pointers.