shubendrak
shubendrak

Reputation: 2068

How this c program is evaluating

#include <stdio.h>
#define dprintf(expr) printf(#expr "=%d\n",expr)

int main()
{
    int x=7;
    int y=3;
    dprintf(x/y);
    return 0;
}

I am getting output as x/y=2 I am confused how "x/y" is getting printed

Upvotes: 2

Views: 1614

Answers (2)

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158599

In a macro the # stringifies the operands so #expr will take the arguments and turn them into a string and since adjacent string literals are concatenated it will be then be concatenated to "=%d\n" so you end up with:

printf( "x/y" "=%d\n",expr)

which will become:

printf( "x/y=%d\n",expr)

For complete sake from the draft C99 draft standard section 6.10.3.2 The # operator paragraph 2 covers the # it is rather long and hard to read so I won't quote it but section 5.1.1.2 Translation phases paragraph 6 says:

Adjacent string literal tokens are concatenated

Upvotes: 5

Digital Trauma
Digital Trauma

Reputation: 16016

dprintf(x/y);

expands to

printf("x/y" "=%d\n", x/y);

which is evaluated as:

printf("x/y" "=%d\n", 7 / 3);

now since x and y are integers, the result of x/y is 2 (an integer)

so the output is x/y=2

Note the c preprocessor # directive replaces #expr with "expr".

Note also the c compiler will simply concatenate adjacent string literals into one string, i.e. printf("Hello " "World\n"); is equivalent to printf("Hello World\n");

see http://gcc.gnu.org/onlinedocs/cpp/Stringification.html#Stringification for more details.

Upvotes: 1

Related Questions