C Stringizing Operator (`#`)

beginner
9 min

C Stringizing Operator (#)

Welcome to our deep dive into the fascinating world of C programming! Today, we'll explore the C Stringizing Operator, a powerful tool that can help you manipulate strings in your code. Let's get started! 🎯

Understanding the C Stringizing Operator

The # operator, also known as the stringizing operator, is a unique feature of the C preprocessor that converts any token into a string constant. This operator is particularly useful when you want to include a macro's arguments in a string. 💡

Syntax

The syntax for using the stringizing operator is simple: place a # before the ` token you want to convert into a string.

c
#define MY_STRING(x) #x int main() { char str[100] = MY_STRING(Hello, World!); // str now contains "Hello, World!" }

In the above example, we define a macro MY_STRING that takes an argument x. Inside the macro, we use the # operator to convert x into a string. When we call this macro in the main function, it returns the string "Hello, World!".

Practical Application

Let's make this concept more practical by creating a simple logger function. This logger will print a timestamp along with the message you pass to it. 📝

c
#include <stdio.h> #include <time.h> #define LOG_MESSAGE(message) log_ ## message void log_timestamp() { time_t t = time(NULL); struct tm* tm_info = localtime(&t); printf("[%d-%02d-%02d %02d:%02d:%02d] ", tm_info->tm_year + 1900, tm_info->tm_mon + 1, tm_info->tm_mday, tm_info->tm_hour, tm_info->tm_min, tm_info->tm_sec); } int main() { LOG_MESSAGE(info) { printf("Info: This is an info message.\n"); } log_timestamp(); LOG_MESSAGE(error) { printf("Error: This is an error message.\n"); } return 0; }

In this example, we define a macro LOG_MESSAGE that takes a message as an argument and creates a new macro log_ <message>. Inside the macro, we use the stringizing operator to concatenate the timestamp and the message. When we call the macro LOG_MESSAGE in the main function, it expands to log_info and log_error, respectively, and prints the appropriate message along with the timestamp.

Quiz

Quick Quiz
Question 1 of 1

What does the `#` operator do in C programming?

We hope you found this lesson enlightening! Stay tuned for more engaging and informative C programming lessons here at CodeYourCraft. Happy coding! 💡📝