Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
# and ## Operators in C ?
In C, the "#" and "##" are preprocessor operators that are used to manipulate macro parameters during compilation. The # operator converts a macro parameter to a string literal, while the ## operator concatenates two tokens into a single token.
The macro parameters are the parameters of the macro definition, which are declared using the #define directive.
The "#" operator is known as the Stringizing operator, whereas the "##" operator is known as the Token Pasting operator.
Syntax
/* Stringizing operator */ #define MACRO_NAME(param) #param /* Token pasting operator */ #define MACRO_NAME(param1, param2) param1##param2
The Stringizing Operator ('#')
The "#" operator is a preprocessor Stringizing operator in C that converts a macro argument into a string literal. It can only be used within macro definitions −
Example
The following example demonstrates how the Stringize (#) operator converts macro parameters into string literals −
#include <stdio.h> #define STRINGIFY(x) #x #define PRINT_VAR(var) printf(#var " = %d
", var) int main() { int number = 42; /* Convert macro argument to string */ printf("String: %s
", STRINGIFY(Hello World)); /* Print variable name and value */ PRINT_VAR(number); return 0; }
String: Hello World number = 42
The Token Pasting ('##') Operator
The "##" operator is a preprocessor Token Pasting operator that concatenates two macro tokens into a single token. This is useful for creating identifiers dynamically −
Example
The following example shows how the Token pasting (##) operator concatenates tokens −
#include <stdio.h>
#define CONCAT(x, y) x##y
#define DECLARE_VAR(type, name, num) type name##num
int main() {
/* Concatenate numbers */
int result = CONCAT(12, 34);
printf("Concatenated number: %d
", result);
/* Create variable names dynamically */
DECLARE_VAR(int, var, 1) = 100;
DECLARE_VAR(int, var, 2) = 200;
printf("var1 = %d
", var1);
printf("var2 = %d
", var2);
return 0;
}
Concatenated number: 1234 var1 = 100 var2 = 200
Key Points
- The # operator works only with macro parameters, not with regular variables.
- The ## operator creates valid C identifiers by concatenating tokens.
- Both operators are processed during preprocessing, before actual compilation begins.
- These operators cannot be used outside of macro definitions.
Conclusion
The preprocessor operators # (stringizing) and ## (token pasting) are powerful tools for metaprogramming in C. The # operator converts macro arguments to strings, while ## concatenates tokens to create new identifiers dynamically.
