DobbyTheElf
DobbyTheElf

Reputation: 789

Why does this C stringification macro corrupt whilst expanding?

#include <stdio.h>

#define QUOTE(str) #str
#define EXPAND_AND_QUOTE(str) QUOTE(str)
#define TEST one-of-a-linux

int main() {
  printf(EXPAND_AND_QUOTE(TEST)"\n");
}

I get:

one-of-a-1

rather than

one-of-a-linux

Note that "linux" becomes "1" - i.e. the digit one

Upvotes: 2

Views: 196

Answers (4)

ouah
ouah

Reputation: 145899

On my Linux box:

$ gcc -dM -E - < /dev/null | grep 'linux\|unix'
#define __unix__ 1
#define __linux 1
#define __unix 1
#define __linux__ 1
#define __gnu_linux__ 1
#define unix 1
#define linux 1
$

Note the value of unix being 1 on unix platforms has been used in an IOCCC entry. Winner of the "Best One Liner" in 1987.

http://www.ioccc.org/years.html#1987_korn

The code was:

    main() { printf(&unix["\021%six\012\0"],(unix)["have"]+"fun"-0x60);}

Upvotes: 4

Sangeeth Saravanaraj
Sangeeth Saravanaraj

Reputation: 16617

You have a #define for linux to 1 somewhere in your code. The following works fine!

#include <stdio.h>

#undef linux

#define QUOTE(str) #str
#define EXPAND_AND_QUOTE(str) QUOTE(str)
#define TEST one-of-a-linux

int main(void) 
{
    printf(EXPAND_AND_QUOTE(TEST)"\n");
    return 0;
}

Output:

/*
$ gcc mm.c 
$ ./a.out 
one-of-a-linux
$ 
*/

Note:

#define TEST 1linux
#define TEST linux1

prints the expected answers appropriately!

Upvotes: 0

Matt Joiner
Matt Joiner

Reputation: 118590

#undef linux
#define TEST one-of-a-linux

Upvotes: 1

ugoren
ugoren

Reputation: 16441

There's obviously #define linux 1 somewhere (or -Dlinux=1).

Upvotes: 3

Related Questions