03. #pragma, Stringification (#) & Token Concatenation (##)
🔴 Difficulty: Advanced | Advanced Preprocessor Operators, Predefined Diagnostic Macros & #pragma
📖 Definition
The stringification operator (#) converts a macro parameter into a double-quoted string literal. The token concatenation operator (##) merges two separate tokens into a single combined token during macro expansion. The #pragma directive provides compiler-specific control instructions (e.g. #pragma once for header guards).
🎯 Why It Is Used
- Printing Variable Names & Values (
#): Creating assertion or debugging macros that print the literal source code expression along with its evaluated value. - Automatic Code Generation (
##): Generating repetitive variable names, function stubs, or table lookup identifiers programmatically. - Pre-Defined Diagnostic Context: Printing source file names (
__FILE__), line numbers (__LINE__), compilation dates (__DATE__), and function names (__func__) during error logging.
⚙️ How It Works: Built-in Preprocessor Macros
| Pre-defined Macro | Expanded Value | Example Output |
|---|---|---|
__FILE__ | Current source file path string literal | "main.c" |
__LINE__ | Current line number integer constant | 42 |
__DATE__ | Compilation date string literal (MMM DD YYYY) | "Oct 24 2023" |
__TIME__ | Compilation time string literal (HH:MM:SS) | "14:30:00" |
__func__ | Current enclosing function name string (C99) | "process_data" |
📝 Syntax
// 1. Stringification Operator (#)
#define PRINT_EXPR(expr) printf(#expr " = %d\n", (expr))
// 2. Token Concatenation Operator (##)
#define MAKE_VAR(prefix, id) prefix ## _ ## id
// 3. Modern Header Protection Directive
#pragma once
🔀 #pragma once vs Standard #ifndef Guards
While standard #ifndef HEADER_H include guards work across all C compilers, modern C compilers (GCC, Clang, MSVC) support #pragma once. Placing #pragma once at the top of a header file achieves the exact same header protection with faster compilation times.
🌱 Beginner Example: Diagnostic File Location Logging
#include <stdio.h>
void log_checkpoint(const char *msg) {
printf("[%s:%d] Checkpoint in %s(): %s\n",
__FILE__, __LINE__, __func__, msg);
}
int main(void) {
printf("Compiled on: %s at %s\n", __DATE__, __TIME__);
log_checkpoint("System Initialized");
return 0;
}
🌼 Intermediate Example: Printing Expressions with #
#include <stdio.h>
// Converts 'expr' into string literal using #
#define DBG_PRINT_INT(expr) printf("[DEBUG] Expression '%s' evaluates to: %d\n", #expr, (expr))
int main(void) {
int x = 10, y = 20;
DBG_PRINT_INT(x + y); // Prints: Expression 'x + y' evaluates to: 30
DBG_PRINT_INT(x * 5 - y); // Prints: Expression 'x * 5 - y' evaluates to: 30
return 0;
}
🌲 Advanced Example: Token Concatenation ## Stubs
#include <stdio.h>
// Generates variable declarations like: int sensor_temp = 100;
#define DECLARE_SENSOR(type, name, init_val) type sensor_ ## name = (init_val)
int main(void) {
DECLARE_SENSOR(int, temp, 25); // Declares 'int sensor_temp = 25;'
DECLARE_SENSOR(double, voltage, 3.3);// Declares 'double sensor_voltage = 3.3;'
printf("Sensor Temp : %d C\n", sensor_temp);
printf("Sensor Voltage: %.1lf V\n", sensor_voltage);
return 0;
}
🔍 Line-by-Line Explanation
#expr: Converts raw text token passed toDBG_PRINT_INT(x + y)into double-quoted string"x + y".sensor_ ## name: Merges tokensensor_with tokentempto produce new identifiersensor_temp.__FILE__, __LINE__, __func__: Automatically injects current source filename, line number, and function signature at compile time.
💻 Expected Terminal Output
Compiled on: Oct 24 2023 at 14:30:00
[main.c:8] Checkpoint in log_checkpoint(): System Initialized
[DEBUG] Expression 'x + y' evaluates to: 30
[DEBUG] Expression 'x * 5 - y' evaluates to: 30
Sensor Temp : 25 C
Sensor Voltage: 3.3 V
⚠️ Common Mistakes & Pitfalls
- Creating Invalid Identifiers with ##: Concatenating tokens that form invalid C syntax (e.g.
1 ## + 2) causes compilation errors. - Nested Macro Expansion with #: The stringification operator
#prevents inner macro parameters from expanding. Use a double-expansion helper macro when stringifying pre-defined macros like__LINE__!
📌 Important Rules & Limitations
#turns a macro argument into a string literal.##glues two separate tokens into a single token.#pragma onceis widely supported by modern compilers as an alternative to header include guards.
🌐 Multilingual Explanation: English
The # operator converts macro arguments into string literals; ## concatenates two tokens. Built-in macros like __FILE__ and __LINE__ supply source location information for diagnostic logging.
🌐 Multilingual Explanation: Hindi (Roman Script)
Stringification operator # macro argument ko string mein badalta hai, aur ## do tokens ko jodta hai. Built-in macros (__FILE__, __LINE__) se logging mein file naam aur line number milta hai.
🌐 Multilingual Explanation: Marathi (Roman Script)
# operator text la string madhye convert karto, aani ## don tokens la ekatra karto. Logging sathi __FILE__ aani __LINE__ cha vapar kartat.
❓ Practice Questions
- What does the
#operator do when placed before a macro parameter? - What is token concatenation (
##) and how is it used in C macros? - What do the pre-defined macros
__FILE__,__LINE__, and__func__evaluate to?
🚀 Practical Coding Challenge
Write a C program named custom_assert.c that defines a macro CUSTOM_ASSERT(condition) that checks condition and, if false, prints the stringified condition text along with __FILE__ and __LINE__ before terminating.
🧭 Navigation & Breadcrumbs
← Previous: 02. Conditional Compilation | Module 17 Guide | Next Module: 18. Storage Classes →