I am trying to understand what is the flow of replacement of same2, same1 and concatenate in:
#include<stdio.h>
#define concatenate(a,b) a##b
#define same1(a) #a
#define same2(a) same1(a)
main()
{
printf("%s\n",same2(concatenate(1,2)));
printf("%s\n",same1(concatenate(1,2)));
}
I have tried to understand this from many places but I am not able to get it. Can somebody please explain it more clearly?
With
#define concatenate(a,b) a##b
#define same1(a) #a
#define same2(a) same1(a)
when you have same2(concatenate(1,2)), the argument of same2 is expanded before passing it to same1, so there, concatenate(1,2) is replaced by its result, 12 that then is stringified by same1 to produce "12".
With same1, no expansion of the macro argument occurs, since it's preceded by the stringification token #:
After the arguments for the invocation of a function-like macro have been identified, argument substitution takes place. A parameter in the replacement list, unless preceded by a # or ## preprocessing token or followed by a ## preprocessing token (see below), is replaced by the corresponding argument after all macros contained therein have been expanded. Before being substituted, each argument’s preprocessing tokens are completely macro replaced as if they formed the rest of the preprocessing file; no other preprocessing tokens are available.
(section 6.10.3.1 (1) in n1570)
Your concatinate(a,b) becomes concatinate(1,2) when 1 and 2 are passed as parameters. That in turn becomes 1##2 which translates to 12 because ## is a concatenating operator. So parameters 1 and 2 are concatenated to become 12
Same1(a) becomes simply #a, where # is stringisizing operator (See http://c-faq.com/ansi/stringize.html). So Same1(12) becomes "12" and when printed out to console
Same2(a) is the same as Same1(a), which is simply #a, which just outputs parameter a as-is; so the output of Same2(a) where parameter a is 'Concatenate(1,2)' is just a string "Concatenate(1,2)"
Related
I come up with a small example of the problem
Assume I have this macro
#define and ,
And I use it like sum(a and b) which should be expanded to sum(a, b).
My problem here is that if sum is defined by a macro the usage example encounters a too few arguments ... error.
Another problem that I think probably will be related and I guess would be solved by the same trick, is when I define an empty macro and place it between function name and argument list. For example
#define of
Now when I use sum of(1, 2), the compiler treats sum as a function and if it is a macro, then, linker throws an undefined reference error.
#define of
#define sum(a, b) a + b
int main()
{
sum of(a, b); // undefined reference to `sum'
}
Issue with and macro is that a and b is identified as macro argument before replacing and with , happens.
6.10.3.1 Argument substitution
After the arguments for the invocation of a function-like macro have been identified, argument
substitution takes place. A parameter in the replacement list, unless preceded by a # or ## prepro-
cessing token or followed by a ## preprocessing token (see below), is replaced by the corresponding
argument after all macros contained therein have been expanded. Before being substituted, each
argument’s preprocessing tokens are completely macro replaced as if they formed the rest of the
preprocessing file; no other preprocessing tokens are available.
Your second problem is similar but not related. After of is expanded, it is too late to expand sum because it is no longer scanned by the preprocessor:
6.10.3.4 Rescanning and further replacement
After all parameters in the replacement list have been substituted and # and ## processing has
taken place, all placemarker preprocessing tokens are removed. The resulting preprocessing token
sequence is then rescanned, along with all subsequent preprocessing tokens of the source file, for
more macro names to replace.
This is a follow-up question to this one (and also closer to the actual problem at hand).
If I have the following case:
#include <stdio.h>
#define FOO_ONE 12
#define FOO_TWO 34
#define BAR_ONE 56
#define BAR_TWO 78
#define FOO 99
#define STRINGIFY(mac) #mac
#define CONCAT(mac1, mac2) STRINGIFY(mac1) STRINGIFY(mac2)
#define MAKE_MAC(mac) CONCAT(mac##_ONE, mac##_TWO)
#define PRINT(mac) printf(#mac ": " MAKE_MAC(mac) "\n")
void main(int argc, char *argv[])
{
PRINT(FOO);
PRINT(BAR);
}
As can be seen, the stringified, concatenated macros are then substituted inside a printf() statement which itself is inside a macro.
Because FOO is defined (as 99), it happens that it is expanded before the concatenation with _ONE and _TWO, effectively creating the tokens 99_ONE and 99_TWO.
This program outputs:
FOO: 99_ONE99_TWO
BAR: 5678
How can I defer the expansion of the FOO macro (effectively, eliminating it altogether, to get the required output of:
FOO: 1234
BAR: 5678
NOTE: assume the PRINT() macro signature cannot be changed (i.e., can't add a parameter, etc.). However its implementation can be changed. Also, FOO, FOO_* and BAR_* definitions cannot be modified as well.
If you can do something each time FOO is used, you could first undefine the macro inorder for it expand as you want and then redefine it as in
#undef FOO
PRINT(FOO);
#define FOO 99
in which case it will expand to
printf("FOO" ": " "12" "34" "\n");
printf("BAR" ": " "56" "78" "\n");
to print what you want.
How can I defer the expansion of the FOO macro ... NOTE: assume the PRINT() macro signature cannot be changed (i.e., can't add a parameter, etc.)
You can't.
Macro expansions go through a series of steps:
Argument substitution
Paste and stringification in no particular order
Rescan and further replacement
Argument substitution occurs with your arguments; in the case of the invocation PRINT(FOO), FOO; and it's the very first step. By the time you even get the preprocessor to recognize that something in your replacement list is a macro, you've long past argument substitution.
The rule for argument substitution is that if any of your parameters are mentioned in your replacement list, and those parameters are being neither stringified nor pasted, then the corresponding argument is fully evaluated and those mentions of the parameters are replaced with the result. In this case, PRINT(FOO), after argument substitution, results in the replacement list:
printf(#mac ": " MAKE_MAC(99) "\n")
Again, MAKE_MAC's definition doesn't matter; it's not even recognized as a macro until rescan and further replacement.
Now, without your restriction, you could defer FOO from expanding... by adding a second parameter to PRINT and pasting to it (that disqualifies it from a.s., and by the time rescan and replacement comes along it'd be invoking your next macro). But with your restriction, you're DOA.
The actual expansion of FOO to 99 happens at the moment when PRINT is expanded and before its body is re-scanned one more time. The relevant part of the ANSI standard is:
6.10.3.1 Argument substitution
1 After the arguments for the invocation of a function-like macro have been identified,
argument substitution takes place. A parameter in the replacement list, unless preceded
by a # or ## preprocessing token or followed by a ## preprocessing token (see below), is
replaced by the corresponding argument after all macros contained therein have been
expanded. Before being substituted, each argument’s preprocessing tokens are
completely macro replaced as if they formed the rest of the preprocessing file; no other
preprocessing tokens are available.
In your case you can avoid expansion of FOO (inside mac) by replacing
#define PRINT(mac) printf(#mac ": " MAKE_MAC(mac) "\n")
with
#define PRINT(mac) printf(#mac ": " CONCAT(mac##_ONE, mac##_TWO) "\n")
I have a problem with macro expansion deferral. Here is an example:
#include <stdio.h>
#define CONST_ABC 15
#define CONST_5 7
#define ABC 5
#define PRINT(x) printf("CONST=%d\n", CONST_ ## x)
// The problematic macro
#define PRINT2(x) PRINT(x)
int main(int argc, char *argv[])
{
PRINT(ABC); // Prints 15 - OK
PRINT2(ABC); // Prints 7 - Not OK.
}
How to define PRINT2 macro so that it will use PRINT and result would be 15? I'm getting:
CONST=15
CONST=7
And want to get:
CONST=15
CONST=15
It requires you to have at least a C99 compiler, since C99 allows empty macro arguments. However some compilers may allow them as an extension, even in C89 mode. Here is the code:
#include <stdio.h>
#define CONST_ABC 15
#define CONST_5 7
#define ABC 5
#define PRINT(x) printf("CONST=%d\n", CONST_ ## x)
// The problematic macro
#define PRINT2(x, y) PRINT(x ## y)
int main(int argc, char *argv[])
{
PRINT(ABC); // Prints 15 - OK
PRINT2(ABC,); // Prints 7 - Not OK.
}
The second argument (i.e. the y) is empty, making it an empty preprocessing token. The ## operator prevents argument expansion, so the result of the concatenation is the same as x argument.
C11 6.10.3.1/p1 Argument substitution (emphasis mine):
After the arguments for the invocation of a function-like macro have
been identified, argument substitution takes place. A parameter in the
replacement list, unless preceded by a # or ## preprocessing token or
followed by a ## preprocessing token (see below), is replaced by the
corresponding argument after all macros contained therein have been
expanded. Before being substituted, each argument’s preprocessing
tokens are completely macro replaced as if they formed the rest of the
preprocessing file; no other preprocessing tokens are available.
The macro replacement, basically, proceeds as follows:
A token is found, which is a macro name
The arguments of the macro are collected
The arguments are substituted for the formal parameters in the body of the macro definition
Thus substituted parameters are completely macro replaced, not counting the rest the of input; stringification may be performed at this stage as well;
The token paste operators are performed
Thus substituted sequence is re-scanned, together with the rest of the input for further macro replacements
(plus some not well defined rules when a macro is forbidden for replacement)
The only way to prevent a macro argument from being macro-replaced in 4.
is for it to be followed or preceded by a token paste operator (##).
However, in 5. the paste operator has to perform the operation with
the argument under discussion and a special placemarker token. A placemarker token is inserted only for empty argument substitution.
Check this, it might give you an idea for your real code:
#define PRINT2(noreplace,x) PRINT(noreplace ## x)
PS. and yeah, "noreplace" is meant to be empty :)
PRINT2(,ABC)
I came across one more piece of code that is even more confusing..
#include "stdio.h"
#define f(a,b) a##b
#define g(a) #a
#define h(a) g(a)
int main(void)
{
printf("%s\n",h(f(1,2)));
printf("%s\n",g(1));
printf("%s\n",g(f(1,2)));
return 0;
}
output is
12
1
f(1,2)
My assumption was
1) first f(1,2) is replaced by 12 , because of macro f(a,b)
concantenates its arguments
2) then g(a) macro replaces 1 by a string literal "1"
3) the output should be 1
But why is g(f(1,2)) not getting substituted to 12.
I'm sure i'm missing something here.
Can someone explain me this program ?
Macro replacement occurs from the outside in. (Strictly speaking, the preprocessor is required to behave as though it replaces macros one at a time, starting from the beginning of the file and restarting after each replacement.)
The standard (C99 §6.10.3.2/2) says
If, in the replacement list, a parameter is immediately preceded by a # preprocessing
token, both are replaced by a single character string literal preprocessing token that
contains the spelling of the preprocessing token sequence for the corresponding
argument.
Since # is present in the replacement list for the macro g, the argument f(1,2) is converted to a string immediately, and the result is "f(1,2)".
On the other hand, in h(f(1,2)), since the replacement list doesn't contain #, §6.10.3.1/1 applies,
After the arguments for the invocation of a function-like macro have been identified,
argument substitution takes place. A parameter in the replacement list, unless preceded
by a # or ## preprocessing token or followed by a ## preprocessing token (see below), is
replaced by the corresponding argument after all macros contained therein have been
expanded.
and the argument f(1, 2) is macro expanded to give 12, so the result is g(12) which then becomes "12" when the file is "re-scanned".
Macros can't expand into preprocessing directives. From C99 6.10.3.4/3 "Rescanning and further replacement":
The resulting completely macro-replaced preprocessing token sequence
is not processed as a preprocessing directive even if it resembles
one,
Source: https://stackoverflow.com/a/2429368/2591612
But you can call f(a,b) from g like you did with h. f(a,b) is interpreted as a string literal as #Red Alert states.
Is it possible to define a macro off of the content of a macro?
For example:
#define SET(key,value) #define key value
SET(myKey,"value")
int main(){
char str[] = myKey;
printf("%s",str);
}
would result in
int main(){
char str[] = "value";
printf("%s",str);
}
after being preprocessed.
Why would I do this? Because I'm curious ;)
No, its not possible to define a macro within another macro.
The preprocessor only iterates once before the compiler. What you're suggesting would require an undetermined amount of iterations.
No you can't - # in a replacment list of a macro means QUOTE NEXT TOKEN. It's more of a spelling issue, than any logical puzzle :)
(If you require this kind of solution in your code, than there are ways and tricks of using macro's, but you need to be specific about the use cases you need - as your example can be achieved by defining: #define mykey "value")
Here it is from the ansi C99 standard
6.10.3.2 The # operator
Constraints
1 Each # preprocessing token in the replacement list for a
function-like macro shall be followed by a parameter as the next
preprocessing token in the replacement list. Semantics 2 If, in the
replacement list, a parameter is immediately preceded by a #
preprocessing token, both are replaced by a single character string
literal preprocessing token that contains the spelling of the
preprocessing token sequence for the corresponding argument. Each
occurrence of white space between the argument’s preprocessing tokens
becomes a single space character in the character string literal.
White space before the first preprocessing token and after the last
preprocessing token composing the argument is deleted. Otherwise, the
original spelling of each preprocessing token in the argument is
retained in the character string literal, except for special handling
for producing the spelling of string literals and character constants:
a \ character is inserted before each " and \ character of a character
constant or string literal (including the delimiting " characters),
except that it is implementation-defined whether a \ character is
inserted before the \ character beginning a universal character name.
If the replacement that results is not a valid character string
literal, the behavior is undefined. The character string literal
corresponding to an empty argument is "". The order of evaluation of #
and ## operators is unspecified.
Macros are a simple text substitution. Generating new preprocessor directives from a macro would require the preprocessor to continue preprocessing from the beginning of the substitution. However, the standard defined preprocessing to continue behind the substitution.
This makes sense from a streaming point of view, viewing the unprocessed code as the input stream and the processed (and substituted) code as the output stream. Macro substitutions can have an arbitrary length, which means for the preprocessing from the beginning that an arbitrary number of characters must be inserted at the beginning of the input stream to be processed again.
When the processing continues behind the substitution, then the input simply is handled in one single run without any insertion or buffering, because everything directly goes to the output.
whilst it is not possible to use a macro to define another macro, depending on what you are seeking to achieve, you can use macros to effectively achieve the same thing by having them define constants. for example, i have an extensive library of c macros i use to define objective C constant strings and key values.
here are some snippets of code from some of my headers.
// use defineStringsIn_X_File to define a NSString constant to a literal value.
// usage (direct) : defineStringsIn_X_File(constname,value);
#define defineStringsIn_h_File(constname,value) extern NSString * const constname;
#define defineStringsIn_m_File(constname,value) NSString * const constname = value;
// use defineKeysIn_X_File when the value is the same as the key.
// eg myKeyname has the value #"myKeyname"
// usage (direct) : defineKeysIn_X_File(keyname);
// usage (indirect) : myKeyDefiner(defineKeysIn_X_File);
#define defineKeysIn_h_File(key) defineStringsIn_h_File(key,key)
#define defineKeysIn_m_File(key) defineStringsIn_m_File(key,##key)
// use defineKeyValuesIn_X_File when the value is completely unrelated to the key - ie you supply a quoted value.
// eg myKeyname has the value #"keyvalue"
// usage: defineKeyValuesIn_X_File(keyname,#"keyvalue");
// usage (indirect) : myKeyDefiner(defineKeyValuesIn_X_File);
#define defineKeyValuesIn_h_File(key,value) defineStringsIn_h_File(key,value)
#define defineKeyValuesIn_m_File(key,value) defineStringsIn_m_File(key,value)
// use definePrefixedKeys_in_X_File when the last part of the keyname is the same as the value.
// eg myPrefixed_keyname has the value #"keyname"
// usage (direct) : definePrefixedKeys_in_X_File(prefix_,keyname);
// usage (indirect) : myKeyDefiner(definePrefixedKeys_in_X_File);
#define definePrefixedKeys_in_h_File_2(prefix,key) defineKeyValuesIn_h_File(prefix##key,##key)
#define definePrefixedKeys_in_m_File_2(prefix,key) defineKeyValuesIn_m_File(prefix##key,##key)
#define definePrefixedKeys_in_h_File_3(prefix,key,NSObject) definePrefixedKeys_in_h_File_2(prefix,key)
#define definePrefixedKeys_in_m_File_3(prefix,key,NSObject) definePrefixedKeys_in_m_File_2(prefix,key)
#define definePrefixedKeys_in_h_File(...) VARARG(definePrefixedKeys_in_h_File_, __VA_ARGS__)
#define definePrefixedKeys_in_m_File(...) VARARG(definePrefixedKeys_in_m_File_, __VA_ARGS__)
// use definePrefixedKeyValues_in_X_File when the value has no relation to the keyname, but the keyname has a common prefixe
// eg myPrefixed_keyname has the value #"bollocks"
// usage: definePrefixedKeyValues_in_X_File(prefix_,keyname,#"bollocks");
// usage (indirect) : myKeyDefiner(definePrefixedKeyValues_in_X_File);
#define definePrefixedKeyValues_in_h_File(prefix,key,value) defineKeyValuesIn_h_File(prefix##key,value)
#define definePrefixedKeyValues_in_m_File(prefix,key,value) defineKeyValuesIn_m_File(prefix##key,value)
#define VA_NARGS_IMPL(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, N, ...) N
#define VA_NARGS(...) VA_NARGS_IMPL(X,##__VA_ARGS__, 11, 10,9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
#define VARARG_IMPL2(base, count, ...) base##count(__VA_ARGS__)
#define VARARG_IMPL(base, count, ...) VARARG_IMPL2(base, count, __VA_ARGS__)
#define VARARG(base, ...) VARARG_IMPL(base, VA_NARGS(__VA_ARGS__), __VA_ARGS__)
and a usage example that invokes it:
#define sw_Logging_defineKeys(defineKeyValue) \
/** start of key list for sw_Logging_ **/\
/**/defineKeyValue(sw_Logging_,log)\
/**/defineKeyValue(sw_Logging_,time)\
/**/defineKeyValue(sw_Logging_,message)\
/**/defineKeyValue(sw_Logging_,object)\
/**/defineKeyValue(sw_Logging_,findCallStack)\
/**/defineKeyValue(sw_Logging_,debugging)\
/**/defineKeyValue(sw_Logging_,callStackSymbols)\
/**/defineKeyValue(sw_Logging_,callStackReturnAddresses)\
/** end of key list for sw_Logging_ **/
sw_Logging_defineKeys(definePrefixedKeys_in_h_File);
the last part may be a little difficult to get your head around.
the sw_Logging_defineKeys() macro defines a list that takes the name of a macro as it's parameter (defineKeyValue) this is then used to invoke the macro that does the actual definition process. ie, for each item in the list, the macro name passed in is used to define the context ( "header", or "implementation", eg either "h" or "m" file, if you understand the objective c file extensions) whilst this is used for objective c, it is simply plain old c macros, used for a "higher purpose" than possibly Kernighan and Richie ever envisaged. :-)