Skip to content
Tutorials Center
My learning

Topics

Lesson 68 of 135 ยท Preprocessor

Predefined Macros and assert

Learn C's predefined macros - __FILE__, __LINE__, __func__, __DATE__, __STDC_VERSION__ - plus #line, runtime checks with assert and NDEBUG, and static_assert.

Some macros exist before you define anything. The C standard requires every compiler to predefine a small set of them: the current file name, the current line number, the date and time of compilation, and the version of the standard in use. Together with the predefined identifier __func__, they let a program describe where it is in its own source code, which is exactly what you want in error messages, logs and debugging checks.

The most famous user of these macros is assert, the standard way to state "this must be true here" and stop the program with a precise message when it isn't. This lesson covers the predefined macros, #line, how assert works and how NDEBUG switches it off, when to use assertions and when not to, and static_assert, which checks conditions at compile time instead.

Location macros: FILE, LINE and func

  • __FILE__ expands to a string literal with the name of the current source file.
  • __LINE__ expands to an integer constant: the line number where it's used.
  • __func__ isn't a macro but a predefined identifier (C99): inside every function, it behaves like a static const char __func__[] holding that function's name.
C Where am I?

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.

Our editor saves your code as main.c, so that's the file name you see. In a real project, __FILE__ holds the path the compiler was given, for example src/net/socket.c.

Because __func__ is a variable, not a macro, it doesn't exist during preprocessing: you can't paste it into a string literal or stringize it with #. Use it with %s.

Logging the caller's location

Calling a function that prints __LINE__ reports the line inside that function, which isn't useful. A macro, however, expands at the place where it's used, so its __FILE__ and __LINE__ belong to the caller. That's the main reason logging libraries are built on macros:

C A logging macro with source locations

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 messages go to stderr and point at the exact lines of the LOG_ERROR and LOG_WARN calls inside parse_age. Keeping the work in a normal function (log_at) and only the location capture in the macro is good practice: the macro stays tiny and the function is type-checked. Error Handling builds on this idea.

The other standard predefined macros

Macro Meaning
__DATE__ Compilation date as "Mmm dd yyyy", e.g. "Oct 17 2026" (days below 10 have a space: "Oct 7 2026")
__TIME__ Compilation time as "hh:mm:ss"
__STDC__ 1 on a conforming implementation
__STDC_VERSION__ The standard version: 202311L for C23 (see Conditional Compilation)
__STDC_HOSTED__ 1 for a hosted implementation (full standard library), 0 for freestanding (e.g. kernels, firmware)
__STDC_UTF_16__, __STDC_UTF_32__ 1 if char16_t/char32_t values are UTF-16/UTF-32
__STDC_IEC_559__ 1 if float/double follow IEEE 754
__STDC_NO_VLA__, __STDC_NO_THREADS__, __STDC_NO_ATOMICS__, __STDC_NO_COMPLEX__ 1 if that optional feature is missing
C What the compiler tells you about itself

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 first line changes every time, because each run compiles your code fresh. __DATE__ and __TIME__ were popular for "build date" strings, but they make every build different, which defeats reproducible builds (rebuilding the same source should give byte-identical programs). GCC can warn about them with -Wdate-time, and many projects now pass the build date from the build system instead.

Compilers add many non-standard macros as well, such as __GNUC__, __x86_64__ and __COUNTER__ (a counter that increases by one each time it's used, supported by GCC, Clang and MSVC). gcc -dM -E lists them, as shown in The Preprocessor.

#line

#line changes what __LINE__ (and optionally __FILE__) report from that point on. You rarely write it yourself, but code generators such as parser generators (yacc/bison, flex) emit it so that compiler errors point to the original grammar file instead of the generated C:

C
#line 100 "grammar.y"
int x = ;   /* GCC reports: grammar.y:100:9: error: expected expression before ';' token */

After #line 100, the next line is line 100, and so on.

assert: checking assumptions at run time

<assert.h> provides the macro assert(expression). If the expression is true (nonzero), nothing happens. If it's false, assert prints a message with the expression, file, line and function to stderr, then calls abort(), which ends the program immediately and abnormally:

C An assertion that fails (on purpose)

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 first call passes both checks. The second violates the precondition, so the program stops with a message like this one. It begins with the program's name (binary is the name our server gives your compiled program), and the format comes from glibc; other C libraries word it differently:

TEXT
binary: main.c:6: average: Assertion `count > 0 && "average needs at least one value"' failed.

Under the output, the editor adds a note that the program aborted: abort() raises the signal SIGABRT, which ends the process. The && "message" trick works because a string literal is a non-null pointer and therefore always true: it doesn't change the result, but it appears in the printed expression. fflush(stdout) makes sure the first line is printed before the program aborts, since abort() doesn't flush output buffers.

NDEBUG turns assertions off

If the macro NDEBUG ("no debug") is defined at the point where <assert.h> is included, assert(x) expands to ((void)0) and the expression isn't evaluated at all. Release builds commonly pass -DNDEBUG; CMake does it automatically for its Release configuration (see Build Tools):

C NDEBUG removes assertions and their side effects

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 failing assertion is gone, and so is the call to bump(): counter stays 0. The compiler noticed too: without the C23 [[maybe_unused]] attribute, GCC warns 'bump' defined but not used, because after preprocessing nothing calls it. Delete the #define NDEBUG line and the first assert stops the program. This is the most important rule about assert: never put code with side effects inside it. A line like assert(fclose(file) == 0); closes the file in debug builds and silently doesn't in release builds. Do the work first, then assert on the result:

C
int closed = fclose(file);
assert(closed == 0);

When to use assert

Assertions document and check programmer errors: things that can only go wrong if the code itself is buggy.

  • Good: preconditions and invariants, like "this pointer is never NULL here", "the index is within the array", "the list is sorted after this loop".
  • Bad: anything that can fail in a correct program, like a missing file, invalid user input, a full disk or failed malloc. Those need real error handling with return values and messages (Error Handling), because they must still be handled when NDEBUG removes the asserts.

A useful test: if the condition fails, is the right fix to change the code? Then it's an assertion. Is it to tell the user something? Then it's an error check.

static_assert: checking at compile time

Some facts are known while compiling: type sizes, struct layouts, constant values. static_assert(constant-expression, message) checks them during compilation and stops the build with your message if they're false. It costs nothing at run time.

C Compile-time checks with static_assert

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.

All checks pass, so the program runs. Change MAX_PLAYERS to 20 and the build fails with error: static assertion failed: "player ids are stored in 4 bits", before any code runs. static_assert can appear at file scope, inside functions and even inside struct definitions.

Its history explains the spellings you'll meet:

  • C11 added the keyword _Static_assert(expr, "message"); <assert.h> defined static_assert as a macro for it.
  • C23 made static_assert a keyword and the message optional.

Use static_assert for anything the compiler can decide, and assert for what can only be checked while the program runs. Padding and Alignment shows static_assert protecting struct layouts.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A function report() prints __LINE__. You call it from line 40 of main.c. Which line number does it print?

    __LINE__ expands where it's written. To capture the caller's line, wrap the call in a macro so the expansion happens at the call site.
  2. 2. What does assert(count > 0) do when count is 0 and NDEBUG is not defined?

    A failed assert writes a diagnostic to stderr and calls abort(), which ends the program abnormally (SIGABRT). C has no exceptions.
  3. 3. With -DNDEBUG, what happens to assert(save_file(path));?

    With NDEBUG, assert expands to ((void)0) and its argument isn't evaluated. Never put side effects inside assert.
  4. 4. Which check belongs in static_assert rather than assert?

    Type sizes are known while compiling, so static_assert can check them with no run-time cost. The others are run-time conditions, and three of them need real error handling.
  5. 5. Why can't you write #define NAME_STR #__func__ to get the function name as a string literal?

    __func__ behaves like a static const char array created by the compiler. The preprocessor never sees its value, so you use it with %s at run time.

Summary

  • __FILE__ and __LINE__ give the current file and line; __func__ (a predefined identifier, not a macro) gives the function name.
  • Macros expand at the call site, so logging macros can report the caller's location.
  • __DATE__, __TIME__, __STDC__, __STDC_VERSION__, __STDC_HOSTED__ and the __STDC_NO_*__ macros describe the compilation and the implementation.
  • #line changes the reported line and file; code generators use it.
  • assert(expr) aborts with a precise message when expr is false; defining NDEBUG before <assert.h> removes assertions, including their side effects.
  • Use assert for programmer errors and real error handling for things that can fail in correct programs.
  • static_assert checks constant conditions at compile time (C11 _Static_assert; C23 keyword with an optional message).

Next: File Handling Basics