Improperly terminated macro invocation when using # before the replacement text - c

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));
}

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

Related

What is the utility of escape sequence '\'?

In the below code snippet , how is '\' behaving ?
printf("hii\"); // This line gives error : missing terminating " character
printf("hii\ n"); // This line prints hii n
I am unable to get how this escape sequence is behaving here ,Please explain .
An escape sequence isn't the single \ character; it's that followed by another character. For example, \" is an escape sequence, as is \n. Under some circumstances you can see more than a single character following the backslash all as the same escape code; this has to do with how the characters are represented internally (ASCII or Unicode value) and can be safely ignored for now.
An escape sequence is used to write a character that is inconvenient/impossible to put into the code directly. For example, \" is the escape sequence for a quotation mark. It is like putting a quote inside the string, which you couldn't otherwise do because it would instead close the string literal. Look at the syntax highlighting of your question to see what I mean; most of the first line is considered part of the string, because you never have an unescaped closing quote.
The most common escape sequence is perhaps \n. Unlike with \", it doesn't just produce a literal n in the string; you could do that without an escape. Instead it produces a newline. The code
printf("hii\nthere");
prints
hii
there
to the screen.
The second line of code in your question uses the escape sequence \ (backslash space). Thisis not a standard escape sequence; if you compile with warnings your compiler will probably report that it's ignoring it or something.
(If you want to actually print a backslash to the screen, you need to escape a backslash, using \\)

Can use escape character for Double Quote JSON

I have a json without escape character which I my code is unable to parse because there's no escape character. I can make it work by adding a \ before the double quotes. However, due to some constraint I am looking for a workaround and I want to know --
a. Is there any other way I can make this json work without an escape character and the content having double quotes is displayed on my application as is, or
b. do I necessarily need to have an escape character before all double quotes and there's no workaround?
"abc": {
"x1": {
"text1": "key1",
"text2": "Given "Example text" is wrong"
}
}
Thanks !!
Your example is invalid JSON, but I think you know that. :-)
do I necessarily need to have an escape character before all double quotes
Yes, the only way to have a " inside a JSON string is to use an escape of some kind. Unlike JavaScript, JSON doesn't have '-delimited strings or backtick-delimited templates that become strings (new in ES2015). There are a couple of different escape sequences you can use (\" and \u0022 for instance), but they're still escape sequences. After all, the " is how the JSON parser knows it's found the end of the string.
In the specific case of HTML, you could also use " (a named character entity) if you're interpreting the string as HTML. But that doesn't change the fact you need to properly escape the string (since newlines and several other characters need escaping as well, not just ").
My experience is that the best way to produce JSON is to produce a structure in memory and then use the facility of your environment to convert that structure to valid JSON. In JavaScript, that's JSON.stringify; in PHP, it's json_encode; etc. Just about any language or environment you can find has a JSON library (built-in or not) for this.
You SHOULD add escape char () in order to have a valid JSON.
According to the specs, this is the list of special character used in JSON :
\b Backspace (ascii code 08)
\f Form feed (ascii code 0C)
\n New line
\r Carriage return
\t Tab
\" Double quote
\ Backslash caracter

How to escape characters in a string and also show the escaped characters?

How can I place \ before " of a string in C with out parsing the string character by character?
Actually,we are using sprintf to take the string and we are forming JSON response. But JSON is giving us error as it expects \ to be there before ".
For example, if the string is in the format :
"hi "hello" bye"
I should get it in format of
"hi \"hello\" bye"
Just escape the backslash in the sprintf by adding \\ befor \":
json_resp->offset += sprintf(&json_resp->buffer[json_resp->offset],
"\n\\\""JSON_FIELD_EVENT_SYNOPSIS"\\\": \\\"%s\\\",", utf8_str);
You should consider using snprintf to avoid buffer overflows.
Look at it piece by piece, rather than confused by the whole thing in one go.
You want to see a \, which needs escaping: \\.
Next, you want to see ", which also needs escaping : \".
So all together it's:
printf("hi \\\"hello\\\" bye")
It looks nastier and more confusing than it actually is if you break it down as above - there's no special rule to it, it's just stringing (ahem..) characters together that you already know how to escape.

Why aren't standard escape sequences like \a ,\v working?Why ' works without \,and is \? standard?

Why aren't \a (beep),\v(vertical tab) not working in my program even though they are standard according to the links below?And why is a single quotation mark working even without using it as \'? And finally,is \? an escape character at all as that Microsoft site says,because I use the ? symbol inside a printf() format string without \ and it works fine.
To put it clearly:
Why are \a and \v not working?
Why single quote works without the \ even though \' is an escape sequence?
Is \? an escape sequence?(The link says so but ? works without the \)
http://msdn.microsoft.com/en-us/library/h21280bw(v=vs.80).aspx
http://en.wikipedia.org/wiki/Escape_sequences_in_C
Why are \a and \v not working?
Because the console you’re using doesn’t support them. The compiler does, and produces the correct character code in the output, but the terminal emulator ignores them.
Why single quote works without the \ even though \' is an escape sequence?
Because it’s unnecessary to escape it in strings, you only need to escape it in a char literal. Same for \" for string literal:
"'" vs. '\''
'"' vs. "\""
Is \? an escape sequence? (The link says so but ? works without the \)
The link actually says something different:
Note that … \? specifies a literal question mark in cases where the character sequence would be misinterpreted as a trigraph
It’s only there to avoid ambiguity in cases where the following characters would form a valid trigraph, such as ??= (which is the trigraph for #). If you want to use this sequence in a string, you need to escape the first (or second) ?.
Some of the escape sequences are device specific. So they don't produce the desired on effect on every device. For example, the vertical tab (\v) and form feed (\f) escape sequences do not affect screen output. But they do perform the appropriate printer operations.

string literals/escapes

I am wondering if there is some sort of string prefix so that the cstring is taken as is without the need of my escaping all the characters. I am not 100% sure. I remember something about prefixing the string with the # symbol ( char str[] = #"some\text\here"; ) and you would not need to escape any of your characters such as \, \n,.etc. im working with curl and urls and it is a pain to have to escape every single backslash.
can anyone spread some light on this or am i stuck escaping every character prefixed with a backslash?
No. In C there are only two types of "string", the string literal surrounded by double quotes and the char literal surrounded by single quotes.
In both cases you must backslash escape characters that have special meaning.
This feature is not available in C. It seems you read about verbatim string literals of C#
and if you have to escape - escape characters in C you need to escape that using backslash ( \ )
In C, there is no such thing. You are stuck escaping everything, or perhaps you could put your URLs in a file and read them in.

Resources