Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn’t the preprocessor cause two adjacent minus signs to be a decrement? [duplicate]

Tags:

c

preprocessor

Consider the following code:

#include <stdio.h>
#define A -B
#define B -C
#define C 5

int main()
{
  printf("The value of A is %d\n", A); 
  return 0;
}

Here preprocessing should take place in the following manner:

  1. first A should get replaced with -B
  2. then B should get replaced with -C thus expression resulting into --C
  3. then C should get replaced with 5 thus expression resulting into --5

So the resultant expression should give a compilation error( lvalue error ). But the correct answer is 5, how can the output be 5?

Please help me in this.

like image 377
Rishab Shinghal Avatar asked Oct 14 '17 15:10

Rishab Shinghal


1 Answers

It preprocesses to (note the space):

int main()
{
  printf("The value of A is %d\n", - -5);
  return 0;
}

The preprocessor pastes tokens, not strings. It won't create -- out of two adjacent - tokens unless you force token concatenation with ##:

#define CAT_(A,B) A##B
#define CAT(A,B) CAT_(A,B)

#define A CAT(-,B)

#define B -C
#define C 5

int main()
{
  printf("The value of A is %d\n", A); /* A is --5 here—no space */ 
  return 0;
}
like image 185
PSkocik Avatar answered Oct 27 '22 09:10

PSkocik