Amaterasu
Amaterasu

Reputation: 396

Building strings with C preprocessor macros

The following code is from the C Puzzle book (chapter Basic Types 1.1.). I can't get it to work.

#include <stdio.h>

#define PRINT(format,x) printf("x = %format\n",x)

int integer = 5;
char character = '5';
char *string = "5";

main(){
    PRINT(d,string); PRINT(d,character); PRINT(d,integer);
    PRINT(s,string); PRINT(c,character); PRINT(c,integer=53);
    PRINT(d, ( '5' > 5 ));

    {
        int sx = -9;
        unsigned ux = -8;
        PRINT(o,sx); PRINT(o,ux);
        PRINT(o, sx>>3); PRINT(o, ux>>3 );
        PRINT(d, sx>>3); PRINT(d, ux>>3 );
    }
}

The problem is the macro in the third line: #define PRINT(format,x) printf("x = %format\n",x).

Upvotes: 0

Views: 148

Answers (1)

Toby Speight
Toby Speight

Reputation: 30709

The question really is whether any C preprocessor ever did replacement inside string literals. I've never come across one.

What's required is a stringification, using #:

#define PRINT(format,x) printf(#x " = %" #format "\n", (x))

Upvotes: 4

Related Questions