What does # operator do in C++ macros? [duplicate] - c++

This question already has answers here:
What is the compiler seeing with this macro? [closed]
(4 answers)
Closed 1 year ago.
I came across this macro:
#define STR_ERROR(ecode) case ecode: return #ecode;
What does the #ecode part do?
ecode is an int, and this function returns a const char*.
I'm sure that this has been answered already, but my search-foo has abandoned me. ecode itself is specific to this code. Searching for c++ # gives generic information about macros (as well as some numbered lists relating to C++).

According to cppreference:
# operator before an identifier in the replacement-list runs the identifier through parameter replacement and encloses the result in quotes, effectively creating a string literal
Example from Microsoft Docs
#include <stdio.h>
#define stringer( x ) printf_s( #x "\n" )
int main() {
stringer( In quotes in the printf function call );
stringer( "In quotes when printed to the screen" );
stringer( "This: \" prints an escaped double quote" );
}
Result:
In quotes in the printf function call
"In quotes when printed to the screen"
"This: \" prints an escaped double quote"
Google-Fu protip: I just searched for C++ macro #, the Google recommended adding operator at the end, and those docs were on the first page.

Related

Using single quotes with std::cout for printing a string actually prints numbers [duplicate]

This question already has answers here:
What do single quotes do in C++ when used on multiple characters?
(5 answers)
Closed 3 years ago.
#include <iostream>
int main() {
std::cout << 'hello';
return 0;
}
This program output is:
1701604463
I wonder why it actually runs, although the compiler gives a warning message: character constant too long for its type.
What these numbers actually mean, are they garbage digits?
It is multicharacter literal which has type int.
Multicharacter literal, e.g. 'AB', has type int and
implementation-defined value.

Hash symbol after define macro? [duplicate]

This question already has answers here:
# and ## in macros
(3 answers)
Stringification - how does it work?
(2 answers)
Closed 5 years ago.
What does the '#' symbol do after the second define? And isn't the second line enough? Why the first one?
#define MAKESTRING(n) STRING(n)
#define STRING(n) #n
This is stringize operation, it will produce a string literal from macro parameter, e.g. "n". Two lines are required to allow extra expantion of macro parameter, for example:
// prints __LINE__ (not expanded)
std::cout << STRING(__LINE__) << std::endl;
// prints 42 (line number)
std::cout << MAKESTRING(__LINE__) << std::endl;
Hash symbol takes macro argument into a c-string.
For example
#define MAKESTRING(x) #x
printf(MAKESTRING(text));
will print text
And first line is only alternative name for this macro.

Why do 'char' values have to have single quotation marks instead of double? [duplicate]

This question already has answers here:
Single quotes vs. double quotes in C or C++
(15 answers)
Closed 5 years ago.
Goal
At the end, I want to know why C++ doesn't support char letter = "C"; but does support char letter = 'C'; (notice that the quotation marks are different).
Code
I am using Repl.it as a code platform.
#include <iostream>
int main()
{
char letter = "C";
std::cout << letter;
}
Error message
main.cpp: In function 'int main()':
main.cpp:5:19: error: invalid conversion from 'const char*' to 'char' [-fpermissive]
char letter = "C";
They are needed because 'C' and "C" represent completely different types - the first is an integer value, while the second is an array of two characters (the letter 'C' plus an implicit null-terminator). Both are useful, and you need some way of saying which one you want, which is what the different kinds of quotes do.
Single quotes are for single characters whereas double quotes are used to create string literals. They mean different things.
See a more thorough explanation.

Macro definition that matches two strings

I would like to define an expression in C++ with macros and I am having quite a bit of trouble.
The expression is :
MATCH string WITH other_string
where string and other_string do not require " "
For example: MATCH r1 WITH string1 is the result i desire.
The purpose of this macro would be to check if r1 string matches with r2.
(I already have the code for the matching)
UPDATE
I would like to call MATCH hello WITH hi
in my main function
int main(){
MATCH hello WITH hi
}
and call my function from this macro to compare them. **Both hello and hi are unquoted arguments and must be treated as variable names
It is always dubious to use macros to make your code look like a different language. It is probably better to consider using a separate parser for your "meta-language" that generates the C++ code for you.
In this case, since C++ syntax requires some way to indicate the end of a statement (close braces or semi-colon) you are in kind of a jam.
Consider your example:
int main () { MATCH hello WITH hi }
Since hi is the last token before the end of main, there is no chance to fix-up the syntax to match C++ requirements.
You can't do what you want, so you have to do something different
If you really intend to embed this syntax into your C++ code, you need sentinel tokens to allow you to fix-up the syntax. My proposed syntax is:
int main () {
BEGIN_MATCHING
MATCH hello WITH hi
MATCH hello WITH hi
END_MATCHING
};
If this syntax is acceptable, then you can use the following macros.
#define BEGIN_MATCHING ((void)0
#define MATCH ); my_function(
#define WITH ,
#define END_MATCHING );
This will cause the code in the proposed syntax example to expand to:
int main () {
((void)0
); my_function( hello , hi
); my_function( hello , hi
);
}
Live Demo
Simply stringify your arguments with #, something like:
#define MATCH_WITH(str1, str2) MATCH #str1 WITH #str2
That way:
MATCH_WITH(testing, testing)
becomes:
MATCH "testing" WITH "testing"

What Kind Of Macro Is this?

I came across this following code:
#include<stdio.h>
#define d(x) x(#x[3])
int main(){
d(putchar);
}
Which prints c as the output. I wonder what does the macro #define d(x) x(#x[3]) does? In C language is there an operator like #? I can see this inside the macro body i.e here x(#x[3]). According to my normal eye it looks something different I see in C language but actually What does this does?
Edit : Whats the real use of # in real world?
I'm a novice in C and it will be good if the explanation is in simple terms. Thanks in advance.
The character '#' is a stringizer -- it turns a symbol into a string. The code becomes
putchar("putchar"[3]);
The hash sign means "stringify", so d(x) expands to putchar("putchar"[3]), whence the c.
From here:
Function macro definitions accept two special operators (# and ##) in the replacement sequence:
If the operator # is used before a parameter is used in the replacement sequence, that parameter is replaced by a string literal (as if it were enclosed between double quotes)
#define str(x) #x
cout << str(test);
Put simply, it changes the "x" parameter into a string. In this case test becomes a char array containing 't', 'e', 's', 't', '\0'.
The # is a pre-processor operator which turns a literal into a string. In fact your d macro prints the fourth char of the converted string of your literal.