liveBook · Manning

String_literal

As explained in Modern C, Third Edition

string_literal is a book-specific function-like macro that accepts a string literal by requiring adjacent empty string literals in its replacement.

The function-like macro string_literal checks an argument by placing it between empty string literals in its expansion: "" X "". Consecutive string literals concatenate, so a literal fits this form; an ordinary character array or pointer does not. section 17.2 section 5.3

string_literal("hello");  // "" "hello" ""
char word[25] = "hello";
...
string_literal(word);     // "" word ""     // Error

The literal argument forms three consecutive string literals. The array argument leaves an identifier between them, producing an error. section 17.2

This check is useful when a function needs a format string that cannot be modified. A C function interface cannot prescribe all the desired properties at once: a non-null character pointer to immutable, zero-terminated text. Even an array parameter written with [static 1] does not enforce this literal requirement. section 17.2

String literals are read-only, although their type is not const-qualified. Treating a modifiable character buffer as a format string can be dangerous: an erroneous or malicious change can make the format invalid and crash the program. section 5.6.1 section 17.2

TAKEAWAY: Use the macro to require a string-literal argument, not to test an arbitrary string at runtime. section 17.2

How Modern C, Third Edition covers it

How deep it goes
Explains the adjacent-literal mechanism and its safety rationale, contrasting it with limitations of function parameter declarations.
Examples
Demonstrates a literal and a character array as arguments, then considers debugging output with a potentially modifiable format string.
What you can do after
Evaluate whether a literal-requiring macro can reject an ordinary character array at a call site.
How it connects
Connects function-like macros, string literals, function parameters, format strings, and const qualification.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.