Jachdich
Jachdich

Reputation: 792

Newline and single double quotes in #define

I'm trying to make a program (just for fun) that requires something like this:

#define TEST "HELLO
#define TEST2 WORLD\n"

...

printf(TEST TEST2);

...

and I want the output to be

HELLO WORLD

however that code does not work.

Is there any way to include newlines and double quotes like this in C?

Upvotes: 1

Views: 843

Answers (2)

Kaz
Kaz

Reputation: 58588

You can't do that; the replacement sequence of a macro consists of complete tokens. Macros work at the token level, not the character level. Your example contains unterminated string literal tokens.

There is a ## operator that can be used in macro replacement sequences for catenating tokens, but the inputs to ## cannot be token fragments.

However, in C syntax, adjacent string literal tokens are combined into a single string literal object. For instance "A" "B" means the same thing as "AB".

Thus if we allow ourselves to start with the tokens HELLO and WORLD as our inputs, then we an construct "HELLO WORLD\n" using a macro, like this:

#include <stdio.h>

#define XMAC(A, B) #A " " #B "\n"
#define MAC(A, B) XMAC(A, B)

#define TEST HELLO
#define TEST2 WORLD

int main(void)
{    
  printf("%s", MAC(TEST, TEST2));
  return 0;
}

When it comes to the C preprocessor, you really have to keep your eye on your main goal (such as achieving some overall improvement in program organization), and be prepared to adjust the details of requirements about how it is to be achieved, rather than insist on some very specific approach.

Upvotes: 3

Bathsheba
Bathsheba

Reputation: 234715

Arranging the macros using \" to escape the quotation gives you

#include <stdio.h>

#define TEST "\"HELLO "
#define TEST2 "WORLD\"\n"

int main(void) {
    printf(TEST TEST2);
}

and yields the output "HELLO WORLD"

Upvotes: 5

Related Questions