How to print and store a variable name in string variable?
We strongly recommend you to minimize your browser and try this yourself first
In C, there’s a # directive, also called ‘Stringizing Operator’, which does this magic. Basically # directive converts its argument in a string.
#include <stdio.h> #define getName(var) #var int main() { int myVar; printf("%s", getName(myVar)); return 0; } |
chevron_right
filter_none
Output:
myVar
We can also store variable name in a string using sprintf() in C.
# include <stdio.h> # define getName(var, str) sprintf(str, "%s", #var) int main() { int myVar; char str[20]; getName(myVar, str); printf("%s", str); return 0; } |
chevron_right
filter_none
Output:
myVar
This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Can we access global variable if there is a local variable with same name?
- Internal static variable vs. External static variable with Examples in C
- Why variable name does not start with numbers in C ?
- How to Count Variable Numbers of Arguments in C?
- Variable length arguments for Macros
- Redeclaration of global variable in C
- Variable Length Arrays in C and C++
- Set a variable without using Arithmetic, Relational or Conditional Operator
- C | Variable Declaration and Scope | Question 1
- C | Variable Declaration and Scope | Question 2
- C | Variable Declaration and Scope | Question 3
- C | Variable Declaration and Scope | Question 4
- C | Variable Declaration and Scope | Question 6
- C | Variable Declaration and Scope | Question 7
- C | Variable Declaration and Scope | Question 8
- Different ways to declare variable as constant in C and C++
- Variable Length Argument in C
- Different ways to initialize a variable in C/C++
- How to modify a const variable in C?
- Name Mangling and extern "C" in C++

