C Foundations
Core types, control flow, functions, arrays, strings, ownership and lifetimes, expected errors, separate build stages and tests. Introductory c17 subset only.
Audience: Learners who have practiced basic control flow and can invoke an installed compiler.
Practice: 5 to 7 hours.
Runtime and boundaries: Export one entry source and any companion files to a fresh practice folder. Compile with clang -std=c17 -Wall -Wextra -Wpedantic -Werror "C 01 Values.c" -o "Atlas example", then run ./"Atlas example" only after compilation succeeds. The C two-file example also needs "Atlas math.c" on the command line. These are recorded installed tools; do not run a package manager. The browser exports source only and never invokes the compiler. Use separate fresh directories to avoid executing stale output. Exact test environment: Apple Clang 21.0.0 (clang-2100.3.34.2); arm64 macOS 27.0.1.
Lessons
Choose C17 deliberately
C and C++ are separate languages. Compile .c files with clang -std=c17; this pack uses a hosted subset, not every C17 facility. Apple Clang 21.0.0 is the tested implementation. Integer widths, plain-char signedness, object layout and diagnostics vary; the examples avoid relying on a specific int width.
Build stages are distinct
Preprocessing includes headers, compilation checks and translates each translation unit, and linking resolves definitions. A declaration in a header is not a separately linked definition. A successful build does not demonstrate expected output. The harness checks syntax, creates objects, links and executes in fresh directories.
Values and control flow
Initialize objects before reading them, use matching printf format specifiers and keep conditions explicit. Signed integer overflow is undefined behavior. Tiny fixed values make simple examples tractable; the checked-addition exercise checks limits before adding.
Functions carry contracts
An int pointer alone does not communicate a valid length or lifetime. A function taking a pointer and count depends on the caller providing actual live elements. Use return status plus an output value for expected failures, and avoid using an output value unless the call succeeded.
Arrays and strings need bounds
Arrays hold a fixed number of elements. Most array expressions convert to pointers, so a pointer parameter loses the array bound. C strings require a zero terminator. Bound formatting, check truncation, and do not use unchecked strcpy, gets or unbounded input recipes. Byte lengths are not Unicode text lengths.
Storage duration and ownership
Automatic objects live for their scope; string literals have static storage duration. Allocated storage lasts until it is freed. Establish one responsible owner, check allocation, release once and stop using all aliases afterward. Returning a pointer to a local object or reading freed storage is not a valid teaching pattern.
Errors and tests
Check conversion status, end pointers and range policy. Expected invalid data is different from undefined behavior. assert provides test checks only while NDEBUG is undefined; input validation needs ordinary control flow. Deliberately invalid source fixtures are compiler rejection tests and are never executed.
Practice within limits
All inputs are authored, tiny and local. The harness also runs accepted examples with installed AddressSanitizer and UndefinedBehaviorSanitizer when verified available. These can detect some faults on executed paths; they do not prove safety or general correctness. No file I/O, arbitrary pointers, networking, concurrency, production integration or allocation-failure injection is included.
Reference cards
Entry: int main(void)
Hosted C entry point returns a process status.
Boolean: #include <stdbool.h>
C17 bool, true and false macros.
Output: printf("%d", value)
Format must match promoted argument type.
Length: size_t / %zu
Unsigned size type and matching printf conversion.
Branch: if (condition) { ... }
An explicit conditional block.
Loop: for (size_t i = 0; i < count; ++i)
Index only valid elements.
Function: bool operation(int input, int *out)
Separate success from result.
Read-only access: const int *values
Does not grant ownership or validate lifetime.
Array length: sizeof a / sizeof a[0]
Only at an actual array, not a pointer parameter.
Formatting: snprintf(buffer, capacity, ...)
Check negative return and required size.
String length: strlen(terminated_string)
Requires a valid terminator; counts bytes.
Allocation: calloc(count, sizeof *pointer)
Check failure; bound count and lifetime.
Release: free(pointer)
Release owned allocated storage once.
Conversion: strtol(text, &end, 10)
Check no-conversion, trailing content and ERANGE.
Test: assert(condition)
Can disappear when NDEBUG is defined.
Stages: -fsyntax-only / -c / link / run
Different checks with different failure modes.
Supporting configuration: Build instructions.txt
Export one entry source and any companion files to a fresh practice folder. Compile with clang -std=c17 -Wall -Wextra -Wpedantic -Werror "C 01 Values.c" -o "Atlas example", then run ./"Atlas example" only after compilation succeeds. The C two-file example also needs "Atlas math.c" on the command line. These are recorded installed tools; do not run a package manager. The browser exports source only and never invokes the compiler. Use separate fresh directories to avoid executing stale output.
Examples and practice
Code below is reading material, not an execution console. Download the edition for the complete example files and companion modules.
C 01 - Types and output
C17 uses stdbool.h for bool. Format specifiers must match argument types. Division by a floating operand produces a floating result; the display rounds to two decimal places.
#include <stdbool.h>
#include <stdio.h>
int main(void) {
const int minutes = 25;
const double hours = minutes / 60.0;
const bool ready = minutes > 0;
printf("Minutes: %d\nHours: %.2f\nReady: %s\n",
minutes, hours, ready ? "yes" : "no");
return 0;
}
Expected:
Minutes: 25 Hours: 0.42 Ready: yes
Intentionally invalid C: expected compiler diagnostic containing const-qualified. Expected rejection; not a successful program. No runtime execution follows rejection.
int main(void) { const int n = 1; n = 2; return n; }C 02 - Branches and loops
The loop is bounded and the small integer sum cannot overflow. Braces make the scope of each branch explicit. Do not generalize the arithmetic bound to arbitrary input.
#include <stdio.h>
int main(void) {
int total = 0;
for (int n = 1; n <= 4; ++n) {
if (n % 2 == 0) { total += n; }
}
printf("Even total: %d\n", total);
return 0;
}
Expected:
Even total: 6
C 03 - A checked function
Return status separately from an output value. A non-null output pointer must also point to a live writable int; a null check alone cannot validate pointer lifetime or ownership.
#include <stdbool.h>
#include <stdio.h>
static bool valid_minutes(int n) { return n >= 0 && n <= 120; }
static bool double_minutes(int n, int *out) {
if (out == NULL || !valid_minutes(n)) { return false; }
*out = n * 2;
return true;
}
int main(void) {
int result = 0;
if (!double_minutes(20, &result)) { return 1; }
printf("Double: %d\n", result);
printf("Invalid rejected: %s\n",
!double_minutes(-1, &result) ? "yes" : "no");
return 0;
}
Expected:
Double: 40 Invalid rejected: yes
Intentionally invalid C: expected compiler diagnostic containing too few arguments. Expected rejection; not a successful program. No runtime execution follows rejection.
static int twice(int n) { return n * 2; }
int main(void) { return twice(); }C 04 - Arrays and lengths
The count expression works where values is an array, not after it becomes a pointer parameter. For a nonzero count the caller must supply that many live elements, and every intermediate sum as well as the final sum must fit int. The empty case never dereferences NULL.
#include <stddef.h>
#include <stdio.h>
static int total(const int *values, size_t count) {
int result = 0;
for (size_t i = 0; i < count; ++i) { result += values[i]; }
return result;
}
int main(void) {
const int values[] = {10, 20, 30};
const size_t count = sizeof values / sizeof values[0];
printf("Count: %zu\nTotal: %d\n", count, total(values, count));
printf("Empty: %d\n", total(NULL, 0));
return 0;
}
Expected:
Count: 3 Total: 60 Empty: 0
C 05 - Bounded string formatting
A C string needs a terminating zero byte. snprintf reports the number of characters that would have been written, excluding the terminator. Check negative returns before conversion. strlen counts bytes here, not user-perceived Unicode characters.
#include <stdio.h>
#include <string.h>
int main(void) {
char label[16];
int n = snprintf(label, sizeof label, "%s:%d", "Read", 20);
if (n < 0 || (size_t)n >= sizeof label) { return 1; }
printf("%s (%zu bytes)\n", label, strlen(label));
char tiny[4];
n = snprintf(tiny, sizeof tiny, "%s", "abcdef");
if (n < 0) { return 1; }
printf("Truncation detected: %s\n",
(size_t)n >= sizeof tiny ? "yes" : "no");
return 0;
}
Expected:
Read:20 (7 bytes) Truncation detected: yes
C 06 - Structs and explicit state
Struct assignment copies member values. The title pointer is copied, not the pointed-to text. Both point to the same string literal with static lifetime; neither code path writes through it.
#include <stdio.h>
enum State { OPEN, DONE };
struct Task { const char *title; int minutes; enum State state; };
int main(void) {
struct Task task = {"Read", 20, OPEN};
struct Task copy = task;
copy.state = DONE;
printf("%s: %d\n", task.title, task.minutes);
printf("Original open: %s; copy done: %s\n",
task.state == OPEN ? "yes" : "no",
copy.state == DONE ? "yes" : "no");
return 0;
}
Expected:
Read: 20 Original open: yes; copy done: yes
C 07 - One allocation and one owner
This function owns one small allocation, checks failure, uses it only during its lifetime, then frees it once. Assigning NULL only changes this pointer; it would not repair dangling aliases. Prefer fixed arrays when dynamic storage is unnecessary. Allocation failure is handled but not fault-injected by this pack.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
const size_t count = 3;
int *values = calloc(count, sizeof *values);
if (values == NULL) { fputs("Allocation failed\n", stderr); return 1; }
for (size_t i = 0; i < count; ++i) { values[i] = (int)i + 1; }
printf("Values: %d %d %d\n", values[0], values[1], values[2]);
free(values);
values = NULL;
puts("Owner released storage");
return 0;
}
Expected:
Values: 1 2 3 Owner released storage
C 08 - Parse and report errors
For these valid zero-terminated strings, strtol supplies an end pointer and range status. This policy accepts leading whitespace and a sign if the final value is in range; it rejects trailing content. The output is only assigned after success.
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
static bool parse_minutes(const char *s, int *out) {
if (s == NULL || out == NULL) { return false; }
char *end = NULL;
errno = 0;
long value = strtol(s, &end, 10);
if (s == end || *end != '\0' || errno == ERANGE ||
value < 0 || value > 120) { return false; }
*out = (int)value;
return true;
}
int main(void) {
const char *inputs[] = {"20", "x", "121", "15tail"};
for (size_t i = 0; i < 4; ++i) {
int value = 0;
if (parse_minutes(inputs[i], &value)) { printf("%d\n", value); }
else { puts("invalid"); }
}
return 0;
}
Expected:
20 invalid invalid invalid
C 09 - Compile and link two files
The header declares the contract; a separate .c file defines it. Compile both source files and link their objects, or pass both .c files to one compiler invocation. The function contract is a value from 0 to 120.
#include <stdio.h>
#include "Atlas math.h"
int main(void) {
printf("Double: %d\n", atlas_double(6));
return 0;
}
Expected:
Double: 12
Companion file: Atlas math.h
#ifndef ATLAS_MATH_H #define ATLAS_MATH_H int atlas_double(int value); /* caller supplies 0..120 */ #endif
Companion file: Atlas math.c
#include "Atlas math.h"
int atlas_double(int value) { return value * 2; }
Intentionally invalid C: expected compiler diagnostic containing format specifies type. Expected rejection; not a successful program. No runtime execution follows rejection.
#include <stdio.h>
int main(void) { printf("%d\n", "text"); return 0; }C exercise A - An empty average
At most ten values in 0..120 keeps the sum bounded. The caller still owns the array and must supply n actual live elements. Failure leaves the output unchanged.
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
static bool average(const int *xs, size_t n, double *out) {
if (xs == NULL || out == NULL || n == 0 || n > 10) { return false; }
int sum = 0;
for (size_t i = 0; i < n; ++i) {
if (xs[i] < 0 || xs[i] > 120) { return false; }
sum += xs[i];
}
*out = (double)sum / (double)n;
return true;
}
int main(void) {
const int xs[] = {10, 20}; double result = 0;
if (!average(xs, 2, &result)) { return 1; }
printf("Average: %.1f\n", result);
puts(!average(NULL, 0, &result) ? "empty rejected" : "unexpected");
return 0;
}
Expected:
Average: 15.0 empty rejected
Practice: Return an explicit success status for an average. Reject an empty input, more than ten entries or out-of-range minutes without dividing by zero.
C exercise B - Checked addition
Check limits before performing signed addition. Signed overflow is undefined behavior; checking the result afterward is too late. The subtraction guards are themselves valid for their sign branches.
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
static bool add(int a, int b, int *out) {
if (out == NULL || (b > 0 && a > INT_MAX - b) ||
(b < 0 && a < INT_MIN - b)) { return false; }
*out = a + b;
return true;
}
int main(void) {
int result = 0;
if (!add(10, 20, &result)) { return 1; }
printf("Sum: %d\n", result);
puts(!add(INT_MAX, 1, &result) ? "upper rejected" : "unexpected");
puts(!add(INT_MIN, -1, &result) ? "lower rejected" : "unexpected");
return 0;
}
Expected:
Sum: 30 upper rejected lower rejected
Practice: Add two ints only when their mathematical sum fits int. Demonstrate both boundary rejections without actually overflowing.
C exercise C - Runtime assertions
These four runtime assertions run with NDEBUG undefined in the test build. assert can be compiled out and is not a substitute for validating external input in released software.
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
static bool valid_minutes(int n) { return n >= 0 && n <= 120; }
int main(void) {
assert(valid_minutes(0));
assert(valid_minutes(120));
assert(!valid_minutes(-1));
assert(!valid_minutes(121));
puts("Assertions: 4 passed");
return 0;
}
Expected:
Assertions: 4 passed
Intentionally invalid C: expected compiler diagnostic containing static assertion failed. Expected rejection; not a successful program. No runtime execution follows rejection.
_Static_assert(sizeof(char) == 2, "deliberate failure");
int main(void) { return 0; }Practice: Write four boundary assertions for inclusive 0..120. Explain why a successful compilation does not prove these assertions were executed.
Prompt templates
These are editable planning prompts in the downloadable workbench; they do not contact an AI service here.
Build a bounded example
For {language}, help me {goal}. Environment: {runtime}. Constraints: {constraints}. Return complete source and companion files, exact compiler flags, expected output and resource ownership. Do not claim tests ran without evidence.Diagnose a build or runtime failure
For {language}, help me {goal}. Environment: {runtime}. Constraints: {constraints}. Separate compiler, linker and runtime symptoms. Show a minimal correction and a regression check. Do not claim tests ran without evidence.Design boundary tests
For {language}, help me {goal}. Environment: {runtime}. Constraints: {constraints}. Cover empty, boundary and rejected input. Separate static rejection fixtures from successful programs and actual execution. Do not claim tests ran without evidence.Refactor with clear ownership
For {language}, help me {goal}. Environment: {runtime}. Constraints: {constraints}. Preserve output and explain lifetimes, bounds and ownership before and after the change. Do not claim tests ran without evidence.Document a contract
For {language}, help me {goal}. Environment: {runtime}. Constraints: {constraints}. State pointer/view preconditions, ranges, outputs, failure behavior, compiler mode and unsupported cases. Do not claim tests ran without evidence.Review lifetime and arithmetic risks
For {language}, help me {goal}. Environment: {runtime}. Constraints: {constraints}. Check dangling views, invalid bounds, format mismatches, unchecked allocation and integer overflow. Do not introduce deliberate undefined behavior. Do not claim tests ran without evidence.Further reading
- WG14 N1570 C11 committee draft — Core objects, arrays, functions, storage duration, formatted output, allocation and conversion semantics used in the C17 subset; not a C17 draft or full-conformance claim.
- Clang compiler user manual — Compiler driver, standard modes and diagnostics; upstream documentation is not an Apple feature guarantee.
- Clang C implementation status — C mode support and known limits; actual examples pin Apple Clang C17.
- Clang AddressSanitizer — Instrumented checking of some memory errors on executed paths; not safety proof.
- Clang UndefinedBehaviorSanitizer — Checks for selected undefined behavior; coverage is incomplete.
Download the offline edition
Complete Atlas 0.11.0 ZIP (6,079,970 bytes) · 411-page guide and catalogue PDF · Versioned source JSON
Unzip the edition and open Programming and Scripting Atlas.html, Web Foundations.html, Python Foundations.html, SQL Foundations.html, Shell Foundations.html, TypeScript Foundations.html Data Formats Foundations.html, C Foundations.html C++ Foundations.html, Ruby Foundations.html, Perl Foundations.html, Swift Foundations.html, Makefile Foundations.html, awk Foundations.html, sed Foundations.html, jq Foundations.html, XSLT 1.0 Foundations.html, Tcl Foundations.html, Expect Foundations.html or Objective-C Foundations.html locally. The original interactive workbenches retain their offline prompt-building, local presets and export controls. Read the included README before running examples yourself. The workbench does not execute pasted code or call an AI service; prompt text is for you to inspect and use separately.
Version 0.11.0 is pinned here. The other 257 registry entries remain planned; this edition does not claim complete language coverage.
Evidence and limits
Objective-C adds 12 accepted native programs, four separate compiler or warning-policy rejections, 120 root checks and 147 independent native checks. Two rejection fixtures are warnings promoted by -Werror; they are not intrinsic syntax failures. No rejected fixture was executed. Tests dated 26 October 2026 used Apple Clang 21.0.0, ARC, C17 base mode, macOS SDK 27.0 headers and system Foundation 6.9 (5027.0.69) on macOS 27.0.1 arm64. This is introductory macOS/Foundation coverage, not iOS, GNUstep, Objective-C++, UI, concurrency or cross-platform coverage. No sanitizers, leak detector, race analysis, allocation/disk-full/permission fault injection or asynchronous timing tests were run. Trusted authored fixtures and process bounds do not establish an arbitrary-code sandbox.
The pinned Atlas 0.11.0 evidence records 607 browser checks, 55 Python harness checks plus four unittest methods, 74 SQL checks, 515 shell checks across 71 runs, 99 TypeScript checks, 51 Data Formats checks, 119 C checks, 116 C++ checks, 97 Ruby checks, 97 Perl checks, 105 Swift harness checks and 97 Makefile harness checks, 145 awk checks, 145 sed checks, 161 jq checks, 157 XSLT checks, 150 Tcl checks and 161 Expect checks. These are separate measures. Tcl and Expect tests are dated 26 October 2026 on installed Tcl 8.5.9 / Expect 5.45 with Tcl 8.5.9 on macOS arm64. These old versions are recorded teaching evidence, not deployment recommendations. Tcl has 12 accepted programs and Expect has 12 accepted controllers; each has four expected evaluation failures, not static compilation passes. Tcl has nine scenarios, five expected nonzero; Expect has seven scenarios, four expected nonzero. Expect default controllers invoke 15 toy children, including two expected child failures; one scenario also expects a failed child. Controller success does not mean every child succeeds. The authoring release records 100 owned-runner regression checks and 109 independent runner checks separately. Only authored fixtures and retained native child handles are covered. Cooperative cleanup requires event-loop progress; outer-timeout child cleanup remains uncertain without complete wait receipts. The retired PID-inspection branch was not retried. No sign-ins, secrets, network or external application control are taught or tested by this pack. awk and sed are text-processing languages; their examples use fixed authored ASCII input and the C locale with installed awk 20200816 and macOS sed on one platform. jq and XSLT each have 12 accepted examples and four separately rejected programs. jq has 21 scenarios, including five contract errors and one no-result status; XSLT has 20 scenarios, including five terminating messages and one CLI parameter rejection. Expected nonzero outcomes are not successful programs. Tests dated 26 October 2026 used jq 1.7.1-apple and XSLT 1.0 with libxslt 1.1.35/libxml2 2.9.13, fixed trusted programs and tiny authored inputs in the C locale on macOS arm64. These old installed XML libraries are recorded learning environments, not recommendations for untrusted-document processing. No imports, external documents, DTDs, custom/external entities, extension functions or generated source are covered. Command flags and bounds are not a complete sandbox. Standalone XPath remains planned; supporting XPath 1.0 expressions are limited to these XSLT examples. These tests do not establish GNU-tool equivalence, Unicode behavior, arbitrary-script safety or cross-platform portability. Swift has 12 accepted programs and four expected static rejections; Makefile has 12 accepted default targets, four expected parser rejections, eight additional scenarios and one expected recipe failure. Makefile is build scripting, not a general-purpose language. The Swift and Makefile test execution dates remain 25 October 2026. awk and sed tests are dated 26 October 2026. Delivery verification does not replace or refresh test execution dates. TypeScript includes 12 accepted programs executed as JavaScript and nine intentionally invalid cases correctly rejected. Each C/C++ pack has 12 accepted programs run normally and with AddressSanitizer/UndefinedBehaviorSanitizer, plus four expected compiler rejections that are never executed. Ruby and Perl each have 12 syntax-accepted programs executed and four expected syntax rejections; rejected cases are not successful programs. Syntax checks may execute compile-time code and are not arbitrary-code sandboxes. Sanitizer results cover executed paths only; leak detection and allocation-failure injection were not tested and memory safety is not proved.
Tested environments are Chrome 155, CPython 3.9.6, SQLite CLI 3.54.0, macOS sh/Bash 3.2.57/Zsh 5.9, TypeScript 6.0.3, Node 24.18.0 Apple Clang 21.0.0, Ruby 2.6.10p210 and Perl 5.34.1, Apple Swift 6.4 in Swift 6 mode and GNU Make 3.81 on one arm64 macOS host. C uses a C17 subset; C++ uses a C++20 subset with libc++ 220106. Python 3.9.6 is unsupported upstream. Ruby 2.6 is end-of-life upstream; the recorded installed interpreter is not a recommended modern runtime. Data Formats uses installed Tomli 1.0.3 through a private fallback; the Python tomllib branch was not run. No new-installation recommendation, complete language/format conformance, schema certification, hardened untrusted XML parsing or general-purpose execution sandbox is established. Other platforms, browsers and screen readers remain unverified. The 145 official references belong to the saved Atlas review, not fresh website-time verification.