Open In App

How to print a variable name in C?

Last Updated : 02 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Printing a variable name means printing the identifier that is assigned to the variable. To print it, it should be in the form of string. This can be done by using stringification.

Stringification in C is the method to convert the argument of a function like macro to a string. This can be done with the help of stringize operator # and define preprocessor. Let’s take a look at an example:

C
#include <stdio.h>

// Macro to stringize the given argument
#define STRINGIZE_THIS(var) #var

int main() {
    int name_of_var = 10;

    // Use the macro to stringize the name of
      // variable and then print it using printf
    printf("%s", STRINGIZE_THIS(name_of_var));

    return 0;
}

Output
name_of_var

Explanation: The name of the variable is passed to the function like macro STRINGIZE_THIS() and it converts it to string by inclosing it in double quotes. Basically it converts the statement STRINGIZE_THIS(name_of_var) to “name_of_var”. Then this string is easily printed by the printf() function.


Next Article

Similar Reads

three90RightbarBannerImg
  翻译: