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 #define getName(var) #var int main() { int myVar; printf("%s", getName(myVar)); return 0; }
Output:
myVar
We can also store variable name in a string using sprintf() in C.
# include # define getName(var, str) sprintf(str, "%s", #var) int main() { int myVar; char str[20]; getName(myVar, str); printf("%s", str); return 0; }
Output:
myVar
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.