0

I am new to C so this question might be dumb. Nevertheless, I was trying to play around with macro.

I was using # to make the replacement text into a quoted string and utilizing the feature that the macro will automatically add escape characters where appropriate.

In VS2019 the following code gives me an error saying improperly terminated macro invocation. Why is that?

#include <stdio.h>

#define toStr(x) #x

main(){
    printf(toStr(the "\" is the escape character));
}
Richard Chambers
  • 16,643
  • 4
  • 81
  • 106
Yilei Huang
  • 77
  • 1
  • 7

1 Answers1

2

As @alinsoar mentioned in their comment, the text string is not properly written. The escape character, '\', escapes the text following according to the rules. The result is that when you have "\" what you have specified is that the quote following the backslash is being escaped which results in the text string not having a terminating quote. See How to print out a slash (/ or \) in C?

To actually print the escape character you need to escape it as in "\\" which will result in a single escape character being printed and the text string is also properly closed with a terminating quote.

See C Preprocessor, Stringify the result of a macro which provides information about the Stringify operator of the C Preprocessor, which is what the # for macro expansion does.

You should review the various rules for the escape character and its usage in C. This list for C++ is pretty much the same as for C. https://en.cppreference.com/w/cpp/language/escape

See as well Explain Backslash in C

Richard Chambers
  • 16,643
  • 4
  • 81
  • 106