Athul
Athul

Reputation: 449

Passing variable name as argument in ## operator

I was learning the use of token parsing operator. When I did as follows,

#include <stdio.h>

#define concat(a, b) a##b

int main(int argc, char** argv)
{
    printf("%d\n", concat(1, 2));
    system("pause");
    return 0;
}

Output : 12

But when I tried to pass arguments as variable name,

#include <stdio.h>

#define concat(a, b) a##b

int main(int argc, char** argv)
{
    int x = 2;
    int y = 3;
    printf("%d\n", concat(x, y));
    system("pause");
    return 0;
}

Got error

'system' undefined; assuming extern returning int   
'xy': undeclared identifier
identifier "xy" is undefined

I read in Stackoverflow as "C macros are really preprocessor macros that are expanded before compilation. The variable 'port', doesn't get set until runtime."

Okay, That's not possible. But when I tried this

#include <stdio.h>

#define mult(a, b) a*b

int main(int argc, char** argv)
{
    int x = 2;
    int y = 3;
    printf("%d\n", mult(x, y));
    system("pause");
    return 0;
}

OUTPUT : 6

Why this has no error, but with ## there's error

Upvotes: 0

Views: 171

Answers (1)

user31264
user31264

Reputation: 6727

Preprocessor doesn't know the C language.

Preprocessor is STUPID. It does not run your program. It just takes the code and mechanically applies changes which you tell him to apply. This changed code is compiled by C compilier.

when you write

#define concat(a,b) a##b
...
int x=2, y=3;
int z=concat(x,y);

It does NOT run the program to determine that x=2, y=3. For preprocessor, int x=2, y=3; is just a silly sequence of tokens whose meaning it doesn't understand. It doesn't even know that x and y are variables. It just knows that concat means concatenation of two tokens. So it produces the code:

...
int x=2, y=3;
int z=xy;

Which then goes to the C compilier.

Upvotes: 3

Related Questions