gcc Stringification of expression with "%" sign

137 Views Asked by At

I`m trying to compile the following program

#include <stdio.h>

#define __stringify_1(x...) #x
#define __stringify(x...)   __stringify_1(x)

#define FOO(expression)\
printf("prefix" __stringify(expression))

int main(int argc, char **argv)
{
   FOO(10 % 4); // <-- This is a problematic one 
   FOO(10 == 4); 
}

This yeilds a warning on compilation: warning: conversion lacks type at end of format [-Wformat=]

The reason for this warning is that expression is actually expaneded to printf("prefix" "10 % 4"), hence compiler expects a "formatter". Is there any solution to pass such expressions to macro without getting a warning ?

Thanks

2

There are 2 best solutions below

0
llllllllll On

Use printf("prefix%s", __stringify(expression)) to disable the formatting impact of expression.

0
H.S. On

From printf:

A % followed by another % character will write a single % to the stream.

So, try double %%, like this:

FOO(10 %% 4);