Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the C preprocessor perform simple string manipulation?

This is C macro weirdness question.

Is it possible to write a macro that takes string constant X ("...") as argument and evaluates to sting Y of same length such that each character of Y is [constant] arithmetic expression of corresponding character of X.

This is not possible, right ?

like image 895
Andrei Avatar asked Sep 01 '25 20:09

Andrei


1 Answers

No, the C preprocessor considers string literals to be a single token and therefore it cannot perform any such manipulation.

What you are asking for should be done in actual C code. If you are worried about runtime performance and wish to delegate this fixed task at compile time, modern optimising compilers should successfully deal with code like this - they can unroll any loops and pre-compute any fixed expressions, while taking code size and CPU cache use patterns into account, which the preprocessor has no idea about.

On the other hand, you may want your code to include such a modified string literal, but do not want or need the original - e.g. you want to have obfuscated text that your program will decode and you do not want to have the original strings in your executable. In that case, you can use some build-system scripting to do that by, for example, using another C program to produce the modified strings and defining them as macros in the C compiler command line for your actual program.

like image 174
thkala Avatar answered Sep 03 '25 13:09

thkala