Reputation: 31
I am concatenating two numbers using the ##
operator. The code gives error when I use variables but works fine when I give direct input.
Gives an error.
[Error] 'xy' undeclared (first use in this function)
#include<stdio.h>
#define join(a, b) a##b ;
int main()
{
int x = 10;
int y = 5;
int res ;
res = join(x, y);
printf("%d",res) ;
return 0 ;
}
Works Fine:
#include<stdio.h>
#define join(a, b) a##b ;
int main()
{
int res ;
res = join(99, 10);
printf("%d",res) ;
return 0 ;
}
Upvotes: 2
Views: 99
Reputation: 22821
The ##
preprocessing operator performs token pasting. And tokens are checked at Compile time.
What do you think this res = join(x, y);
is supposed to mean?
res = xy;
The C
compiler should give a compilation error.
This res = join(99, 10);
means
res = 9910;
Which is valid in C syntax. Also remember that Macros are not type-safe so use casts like this:
res = (int) join(99, 10);
Your code would be valid if you had xy
declared before something like this:
#include<stdio.h>
#define join(a, b) a##b ;
int main()
{
int xy = 100;
int res ;
res = (int) join(x, y);
printf("%d",res) ;
return 0 ;
}
Upvotes: 2
Reputation: 134326
Well, preprocessor MACROS are textual substitution, so in case when you're using variables, after preprocessing your code looks like
res = xy;
now this xy
is an undefined identifier in your code.
OTOH, when you're passing integer constants, you code looks like
res = 9910;
which is perfectly valid.
To elaborate on the working of the ##
operator, quoting C11
, chapter §6.10.3.3 (emphasis mine)
in the replacement list of a function-like macro, a parameter is immediately preceded or followed by a
##
preprocessing token, the parameter is replaced by the corresponding argument’s preprocessing token sequence; [...]
Upvotes: 4