Skip to content
Tutorials Center
My learning

Topics

Lesson 133 of 135 ยท Practice and Review

Unusual C Programs: Quine, Error Kinds, Unreachable Code

Write a C program that prints its own source, see compile, link, runtime and logic errors side by side, learn why GCC stays quiet about unreachable code, and print a name's initials.

Not every classic C exercise is about numbers or sorting. This page collects four that teach something different: a program that prints its own source code, a tour of the four kinds of errors you will meet (and how each one shows up), what unreachable code is and what the compiler does and does not tell you about it, and a small string program that turns a name into initials.

All programs run as they are on our server (GCC 15, -std=c23 -Wall -Wextra). The error examples show what the compiler really printed; the ones that fail to build are read-only, because there is nothing to run.

1. A quine: a program that prints itself

A quine is a program whose output is exactly its own source code. It may not read its own file (that would be cheating); it has to carry a description of itself and build the text from it. The trick has two parts:

  • the program stores most of its own text in a string s;
  • it prints s using s itself as the printf format, feeding it the pieces that cannot be written directly inside a string.

What cannot be written inside the string? The double quote that surrounds the string in the source, and the newlines between the lines. So the format string contains %c where a newline or quote belongs, and the arguments supply the characters by number: 10 is the newline character and 34 is the double quote, in ASCII. And where the string needs to appear inside itself, the format has %s, with s passed as the argument.

Read the output line by line against the code. #include <stdio.h>, then %c (a newline), then const char *s = , then %c (a quote), then %s (the whole string again, between the quotes), then a closing quote, a semicolon and a newline, and finally the text of main, which is the same as in the source because it is part of the string. Six %c and %s markers in order, six arguments in the same order: 10, 34, s, 34, 10, 10.

C 1. A quine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Compare the output with the code. They are the same, character for character. If you change anything (add a space, rename s), you must change it in both places, the string and the code after it, or the output will no longer match. That duplication is the price of a quine.

2. The four kinds of errors

Beginners say "my program has an error" as if it were one thing. Four different things go wrong in four different places, and knowing which one you have tells you where to look.

Compile errors: the compiler cannot understand the code

The compiler rejects the source before any program exists. Here a semicolon is missing after 10:

C
int total = 10
printf("%d\n", total);
TEXT
main.c:6:5: error: expected ',' or ';' before 'printf'
    6 |     printf("%d\n", total);
      |     ^~~~~~

Notice that GCC points at the line after the real mistake. It only noticed the problem when it met printf where it expected a semicolon. When an error message points at a line that looks fine, check the line above it. Fix the first error first, because later messages are often side effects of earlier ones.

Every function was declared, so the compiler is happy. But the linker, which joins the compiled pieces into one program, cannot find a definition:

C
int square(int x);                 /* declaration only */

int main(void) {
    printf("%d\n", square(7));     /* call: fine for the compiler */
    return 0;
}
TEXT
main.c:(.text+0xa): undefined reference to `square'
collect2: error: ld returned 1 exit status

The mention of ld (the linker) and the words undefined reference are the signature. The usual causes are a function that was never written, a source file missing from the build command, or a library missing from the link line (for example -lm for <math.h> functions). See Multi-file programs and Build tools.

Runtime errors: the program starts and then fails

The code compiles and links, and then crashes while running. The next program divides by divisor, which falls from 2 to 0:

C 2. A runtime error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The operating system stops the program with a signal. Integer division by zero gives SIGFPE ("floating-point exception", a misleading name that stuck), and an invalid memory access gives SIGSEGV. C does not have exceptions; an invalid operation is undefined behavior, and on most machines the visible result is a crash. See Divide by zero.

One more detail in the program: the fflush(stdout). When the output goes to a pipe or a file, as it does here, C buffers it, and a crash throws the buffer away. Without the flush, you would see nothing at all from the three lines printed so far, and might conclude that the crash happened at the start. This is why debugging output is often written to stderr, which is not buffered. Remove the fflush line to see the difference.

Logic errors: the program runs, and the answer is wrong

This is the hardest kind, because nothing tells you. The program compiles without a warning, exits normally, and prints a plausible number:

C 3. A logic error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The marks are 7, 8 and 8, so the average is 7.67, but the program prints 7.00. The expression sum / count divides two int values, so the division is done in integers and truncates to 7. Only then is the result converted to double. The conversion happens too late. The fix is to convert before dividing: return (double)sum / count;. Get into the habit of testing with values whose answer you know in advance, and of looking at the type of both operands whenever a division is involved (Arithmetic operators, Type conversions).

Kind When it appears Typical sign Where to look
Compile error When compiling error: with a file and line the reported line and the one before it
Link error When linking undefined reference, ld returned 1 missing definitions, files or libraries
Runtime error While running a crash, a signal, a non-zero exit code invalid operations, bad pointers, unchecked input
Logic error Never reported wrong output your reasoning: test with known answers

Warnings are a fifth category worth taking seriously: they are the compiler's way of saying "this is legal, but probably not what you meant". Compile with -Wall -Wextra and treat each warning as a bug until you have understood it.

3. Unreachable code

Unreachable code is code that no execution path can ever run, for example anything after a return, or a branch whose condition is always false. It is usually a leftover from editing, or a sign of a logic mistake.

Look at first_positive in the program below. The printf after return 1; can never execute.

C 4. Unreachable code and unreachable()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Run it: there is no warning, even with -Wall -Wextra. That surprises people. GCC has an option called -Wunreachable-code, but since GCC 4.5 it does nothing: the compiler does remove dead code when optimizing, but it no longer reports it. Clang does have a working -Wunreachable-code, though it is not part of -Wall. Static analyzers, such as gcc -fanalyzer or clang --analyze, can also report some cases. In short: do not rely on the compiler to find dead code. Delete it when you spot it, and let code review and tests catch the rest.

The default: branch of kind uses another tool: unreachable(), added to <stddef.h> in C23. It is a promise to the compiler that control will never arrive there. The compiler may then optimize on that assumption, for instance by dropping the bounds check on the switch. If the promise is false, the behavior is undefined, so use it only where you can prove it. Here n % 3 is always 0, 1 or 2 for a non-negative n, but for a negative n the remainder can be -1 and the promise would be broken. A safer choice for code that handles untrusted values is a real default: branch that reports an error.

4. The initials of a name

A last small classic: from "grace brewster hopper" print G.B.H.. The pattern is a tiny two-state machine. A flag, at_word_start, is true after whitespace. When the loop sees a letter while the flag is on, it prints that letter in capitals and turns the flag off. Whitespace turns it back on. Because the flag is reset by any amount of whitespace, extra spaces at the start, middle or end do not produce stray initials, which the second test name checks.

C 5. Initials of a name

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The function walks the string with a pointer, stops at the null terminator, and wraps both isspace and toupper calls in a cast to unsigned char, as every <ctype.h> call should (see Characters). This only handles ASCII letters. A name that starts with a multi-byte UTF-8 character would need a library that understands Unicode.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the quine, what do the numbers 10 and 34 passed to printf stand for?

    %c prints the character with the given code. 10 is the newline and 34 is the double quote, characters that cannot be written inside the string without escaping.
  2. 2. A program compiles but fails with "undefined reference to `square'". Which kind of error is this?

    The compiler accepted the call because the declaration was visible. The linker could not find the definition when joining the pieces into a program.
  3. 3. Why does return sum / count; print 7.00 for marks 7, 8 and 8 when the function returns double?

    The type of an expression is decided by its operands, not by where the result goes. int divided by int is integer division. Cast one operand to double first.
  4. 4. What does GCC report for a statement placed after a return statement, with -Wall -Wextra?

    GCC accepts the option for compatibility but ignores it, so dead code is silently accepted. Clang implements the warning, and analyzers can find some cases.
  5. 5. Why does the runtime-error example call fflush(stdout)?

    When stdout is not a terminal it is fully buffered. A fatal signal ends the process without flushing, so earlier printf output can vanish. Flushing, or writing to stderr, keeps it.

Summary

  • A quine carries a copy of its own text in a string, prints it through printf, and uses %c with the codes 10 and 34 for the newline and the quote that the string cannot contain.
  • Compile errors come from the compiler (look at the reported line and the previous one), link errors say undefined reference and come from ld, runtime errors crash while running, and logic errors give wrong answers without any message.
  • Integer division truncates before conversion: write (double)sum / count.
  • Output buffering can hide what was printed before a crash. Use fflush or stderr when debugging.
  • GCC does not warn about unreachable code. Clang's -Wunreachable-code and static analyzers can, and C23 unreachable() is a promise to the optimizer, not a check.
  • A boolean "at the start of a word" flag turns a word-by-word task, such as initials, into a simple loop.

Next: Project: Rock Paper Scissors, the first of three small games where you apply arrays, enums and careful input handling.