0

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?

Jachdich
  • 782
  • 8
  • 23

2 Answers2

4

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"

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • The question asks for output “HELLO WORLD”, but this gives output “"HELLO WORLD"”. Although this answer has been accepted, so maybe it is the question that should be edited. – Eric Postpischil Sep 23 '19 at 17:09
  • @EricPostpischil - methinks the question spec shifted (I’m looking for a project manager - perhaps I’ll offer the OP a job). I’ll leave this the way it is. – Bathsheba Sep 23 '19 at 17:16
  • 1
    @EricPostpischil It is true that this is not exactly what I want however it was easy to 'extrapolate' and get the correct answer. – Jachdich Sep 23 '19 at 17:23
3

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.

Kaz
  • 55,781
  • 9
  • 100
  • 149