9

This is the faulty code

#include<stdio.h>

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

void main (void)
{
        printf(CAT("HELLO","WORLD"));
}

Why it gives that error? How could I fix it?

EDIT

This is what I am trying to do

#define TAG                   "TAG"
#define PRE                   CAT(CAT("<",TAG),">")  
#define POS                   CAT(CAT("</",TAG),">") 

#define XML      CAT(CAT(PRE,"XML SOMETHING"),POS)   

then

printf(XML); 
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
trucos
  • 93
  • 1
  • 4

1 Answers1

10

The result of ## must be a single token, and "HELLO""WORLD" is not a single token. To concatenate strings, simply leave them beside each other:

printf("HELLO" "WORLD");

Or change your macro to remove the ##.

#define CAT(A, B) A B

String literals are concatenated together when there are no intervening tokens between them.

Raymond Chen
  • 44,448
  • 11
  • 96
  • 135
Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
  • what do you refer with "a single token"? how can I do concatenation with preprocessor? – trucos Jun 22 '12 at 12:54
  • 1
    @trucos: Read the last sentence of the answer. There's really no need for a macro here; the compiler already does concatenation for you. – cHao Jun 22 '12 at 12:54
  • 1
    if I don't want a macro I woulnd't be asking, my question is how to do it with a macro =). Perhaps it's not possible – trucos Jun 22 '12 at 12:56
  • 3
    Then read the sentence *before* the last one in the answer. :) The `##` is not necessary if you're just concatenating string literals. – cHao Jun 22 '12 at 12:56
  • 3
    @trucos maybe if you let us know what you are actually trying to do then we could help you better. – Seth Carnegie Jun 22 '12 at 12:58
  • @trucos yes, if you just remove the `##` then it will work as long as all your data is string literals. There's no other way to concatenate strings at compiletime other than to both use literals and just put them side by side in source. – Seth Carnegie Jun 22 '12 at 13:09
  • @SethCarnegie right, seems to be a problem in my compiler =( PICC18 hitech... now it works on GCC,, – trucos Jun 22 '12 at 13:17