Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can the C++ Preprocessor be used on strings?

The preprocessor can be used to replace certain keywords with other words using #define. For example I could do #define name "George" and every time the preprocessor finds 'name' in the program it will replace it with "George".

However, this only seems to work with code. How could I do this with strings and text? For example if I print "Hello I am name" to the screen, I want 'name' to be replaced with "George" even though it is in a string and not code.

I do not want to manually search the string for keywords and then replace them, but instead want to use the preprocessor to just switch the words.

Is this possible? If so how?

I am using C++ but C solutions are also acceptable.

like image 421
fdh Avatar asked Jan 22 '12 23:01

fdh


People also ask

How the preprocessor in C language works on?

The preprocessor provides the ability for the inclusion of header files, macro expansions, conditional compilation, and line control. In many C implementations, it is a separate program invoked by the compiler as the first part of translation.

What command is the C preprocessor?

The C Preprocessor is not a part of the compiler, but is a separate step in the compilation process. In simple terms, a C Preprocessor is just a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. We'll refer to the C Preprocessor as CPP.

What is preprocessor with example in C?

Examples of some preprocessor directives are: #include, #define, #ifndef etc. Remember that the # symbol only provides a path to the preprocessor, and a command such as include is processed by the preprocessor program. For example, #include will include extra code in your program.

What is Stringizing operator in C?

The number-sign or "stringizing" operator (#) converts macro parameters to string literals without expanding the parameter definition. It's used only with macros that take arguments.


1 Answers

#define name "George"

printf("Hello I am " name "\n");

Adjacent string literals are concatenated in C and C++.

Quotes from C and C++ Standard:

For C (quoting C99, but C11 has something similar in 6.4.5p5):

(C99, 6.4.5p5) "In translation phase 6, the multibyte character sequences specified by any sequence of adjacent character and identically-prefixed string literal tokens are concatenated into a single multibyte character sequence."

For C++:

(C++11, 2.14.5p13) "In translation phase 6 (2.2), adjacent string literals are concatenated."

EDIT: as requested, add quotes from C and C++ Standard. Thanks to @MatteoItalia for the C++11 quote.

like image 197
ouah Avatar answered Sep 30 '22 16:09

ouah