5
#include <stdio.h>

#define foo(x, y) #x #y

int main()
{
    printf("%s\n", foo(k, l));
    return 0;
}

Output:
kl

I know that ## does concatenation. From the output it seems that # also does concatenation. Am I correct?

If I am correct then what is the difference between ## operator and # operator?

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
Pankaj Mahato
  • 1,051
  • 5
  • 14
  • 26

3 Answers3

2

# stringifies the parameter. See http://www.cs.utah.edu/dept/old/texinfo/cpp/cpp.html#SEC15

## concatenates strings. See http://www.cs.utah.edu/dept/old/texinfo/cpp/cpp.html#SEC16

keshlam
  • 7,931
  • 2
  • 19
  • 33
1

# turns the argument into a string. So foo(k, l) becomes "k" "l", which is the same as "kl" because in C multiple string literals that are directly next to each other are treated as a single string literals.

If # did concatenation, your printf call would become printf("%s\n", kl); which would produce an error about kl not being defined.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
1

## concatenates the two arguments, # quotes ("Stringification") them. So the compiler sees:

printf("%s\n", "k" "l");

If you use GCC, use -E to see the output of the preprocessor.

This question contains details about concatenation of string literals: Implementation of string literal concatenation in C and C++

Community
  • 1
  • 1
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820