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
Selected Reading
How to print a variable name in C?
In C programming, you can print the name of a variable as a string using the stringizing operator (#) within a macro. This technique is useful for debugging and logging purposes where you want to display variable names along with their values.
Syntax
#define MACRO_NAME(variable) #variable
The # operator converts the macro parameter into a string literal.
Example
Here's how to create a macro that prints variable names −
#include <stdio.h>
#define VariableName(name) #name
int main() {
int age = 25;
char grade = 'A';
float salary = 50000.75;
printf("The variable name: %s
", VariableName(age));
printf("The variable name: %s
", VariableName(grade));
printf("The variable name: %s
", VariableName(salary));
return 0;
}
The variable name: age The variable name: grade The variable name: salary
Enhanced Example: Print Variable Name and Value
You can combine variable names with their values for better debugging −
#include <stdio.h>
#define PRINT_VAR(var) printf("%s = %d
", #var, var)
#define PRINT_CHAR(var) printf("%s = %c
", #var, var)
#define PRINT_FLOAT(var) printf("%s = %.2f
", #var, var)
int main() {
int count = 10;
char letter = 'X';
float price = 99.99;
PRINT_VAR(count);
PRINT_CHAR(letter);
PRINT_FLOAT(price);
return 0;
}
count = 10 letter = X price = 99.99
How It Works
- The
#operator (stringizing operator) converts the macro argument into a string literal - When you call
VariableName(age), it expands to"age" - This happens during preprocessing, before compilation
- The macro works with any valid identifier name
Conclusion
Using the stringizing operator with macros is an effective way to print variable names in C. This technique is particularly valuable for creating debugging utilities and logging functions that display both variable names and their values.
Advertisements
