Take a look at this
#define getFourth( _1,_2,_3, _4,... ) _4 //select the 4th parameter
#define some_type(x) type, x
getFourth
( some_type(1),
some_type(2),
some_type(3)
)
I thought it expands to getFourth(type, 1, type, 2, type, 3) so we shall have 2 selected (since 2 is the 4th parameter). Instead, I got a warning "C4003 not enough actual parameters for macro 'getFourth". It appears that getFourth is treat some_type(1) as the first element, some_type(2) as the 2nd element, some_type(3) as the 3rd. Since it was expecting at least 4 parameters so we have the warning. Can someone please suggest how to fix it?
I thought it expands to getFourth(type, 1, type, 2, type, 3) so we shall have 2 selected (since 2 is the 4th parameter)
That's not how macros work. Macro expansion happens from the outside in. Furthermore, there are two opportunities for expansion: (1) during argument substitution, (2) with the resulting replacement list after that happens. Argument substitution expansion only occurs if the parameter in the macro corresponds to one in the replacement list (and that parameter isn't stringified with the # operator or participating in a paste (##)).
For example, if we had:
#define foo(b,c) b c
getFourth(some_type(1),some_type(2),some_type(3),foo(some_type,(4)),x)
Then getFourth now has 5 parameters, so it can be called. The first step in expansion would be argument substitution; getFourth's replacement list is _4, which only mentions one parameter. The corresponding argument is foo(some_type,(4)). Because _4 isn't being pasted or stringified, the processor can evaluate foo(some_type,(4)). That results in some_type (4), which further expands to type, 4. So now, type, 4 replaces _4. And we're done with argument substitution.
We're left with type, 4. There's one more rescan here, but nothing happens during this step. But note that some_type(1), some_type(2), and some_type(3) not only didn't get evaluated before getFourth, but they didn't get evaluated at all, because nothing in the replacement list mentions them.
Can someone please suggest how to fix it?
So long as the things you want to expand are arguments 1 through 3 of getFourth, they won't even evaluate. But you can make this just a parenthesized list, and then apply the macro, using a trick similar to what I did above:
#define CALL(a,b) a b
CALL(getFourth,(some_type(1),some_type(2),some_type(3))).
Now, getFourth and (some_type(1),some_type(2),some_type(3)) are just arguments to CALL, which mentions both parameters. So during argument substitution, getFourth itself "evaluates" (since this isn't enough to call the object-like macro, it's just left as is), and gets put into a. (some_type(1),some_type(2),some_type(3)) evaluates and gets put into b. That evaluation becomes (type, 1,type, 2,type, 3). So you wind up with getFourth (type, 1,type, 2,type, 3). Now rescan occurs, during which getFourth is called with the arguments you expect.
Related
I'm looking for the technical answer answer here. How is Clojure interpreting these symbols? My current working understanding is that the opening paren '(' is a kind of call that calls the succeeding operator on the operands while the closing paren ')' is a terminate that wraps up the previous evaluation and returns the final value generated (whether function or value).
Any and all details on the truth here would be appreciated. I'm looking to go deep here as well as seeing/knowing every level of abstraction along the way. It bugs me to know that I may have some imaginal thinking going on currently.
(foo x1 x2)
is the syntax for calling a special form or var (function or macro).
So the compiler will analyze the form (foo x1 x2) and will check if foo is a special form (if, try, let*, etc.) and if not, the symbol will be resolved to a var in the context of the current namespace. If that var is macro, then macroexpansion will happen, else the call will be treated as a normal function call.
To prevent treating (foo x1 x2) as a function call you can quote the expression: '(foo x1 x2) and then it will just remain a list of symbols.
More info:
https://clojure.org/reference/special_forms
https://clojure.org/reference/macros
You are trying to do too much at once when you say
'(' is a kind of call that calls the succeeding operator on the operands while the closing paren ')' is a terminate that wraps up the previous evaluation and returns the final value generated
The Clojure evaluation model does not assign semantics to characters directly. Instead, evaluation of a Clojure program goes through two broad phases:
First, read the characters in the source file according to the language's lexical rules, yielding a Clojure data structure
Second, evaluate that data structure, according to the language's evaluation rules, yielding a value
So when we write an expression like (+ (* 4 5) 2), what happens? The reader matches up parentheses to create lists, and yields as its result a list of three elements: the symbol +, another list (containing the symbol * and the numbers 4 and 5), and the number 2.
Next we move to evaluate that expression. Notice, crucially, that at this point there is no trace of parentheses. The textual source of the program is no longer material. We're evaluating a list. Of course, if we printed that list, conventionally we would surround it with parentheses, but that does not concern the evaluator. How do we evaluate this list? Well, the evaluation rule for lists is to, first, evaluate each of the components, and then invoke the first component as a function, passing the remaining components as arguments1. So our list of pending tasks is:
Evaluate +
Evaluate (* 4 5)
Evaluate 2
Invoke the result of (1), passing the results of (2) and (3) as arguments
(1), of course, evaluates to the addition function, (2) evaluates (in a similar manner) to the number 20, and (3) evaluates to the number 2 (since numbers evaluate to themselves). Thus, (4) becomes "Invoke the addition function, passing the numbers 20 and 2 as arguments". Of course, the final result is 22.
1 The rule is actually more complicated than this, because of macros, but for functions this suffices.
The other 2 answers are great. The simple summary is:
foo( x1, x2 ) // Java function call
(foo x1 x2) // Clojure function call
In both cases, the compiler will evaluate any nested function calls in x1 or x2 before calling foo on the resulting values.
How should we interpret the following macro definition using the C++ standard? Notice the main issue is that replacement-list for AA contains embedded comma (for, S)
#define AA for, S //<---note the embedded comma
#define VALUE_TO_STRING(x) ^x!
#define VALUE(x) VALUE_TO_STRING(x)
int _tmain(int argc, _TCHAR* argv[])
{
VALUE(AA)
return 0;
}
I've done a test with VC++2010 and the final result of the above looks like the following without any error but I've problem interpreting the steps that it took to come up with the result using C++03 (or C++11) standard:
int wmain(int argc, _TCHAR* argv[])
{
^for, S!
return 0;
}
I've done some step by step tests with VC++2010. First I commented out the 2nd macro to see what was happening in the first step:
#define AA for, S
//#define VALUE_TO_STRING(x) ^x!
#define VALUE(x) VALUE_TO_STRING(x)
The macro replacement is straight forward and yielded a sequence that looks like another function-like macro having TWO arguments:
int wmain(int argc, _TCHAR* argv[])
{
VALUE_TO_STRING(for, S)
return 0;
}
According to [cpp.rescan] the next step is to re-scan this for more macro names. The question here is should this new macro be interpreted as a function-like macro with 2 arguments or 1 argument "for, S".
The normal interpretation is to consider VALUE_TO_STRING() is given 2 arguments which is invalid and hence a preprocessor error is resulted. But how come the VC++ came up with a result without any error? Obviously, the second step VC++ took was to consider the for, S as 1 single argument which doesn't make sense and isn't defined by the C++ standard.
I've done a test with VC++2010...
MS's preprocessor was never made standard. They phrase it this odd way:
C99 __func__ and Preprocessor Rules ... For C99 preprocessor rules, "Partial" is listed because variadic macros are supported.
In other words, "we support variadic macros; therefore we qualify as partially compliant". AFAIK standard compliance for the preprocessor is considered very low priority by the MS team. So I wouldn't tend to use VC or VC++ as a model of the standard preprocessor. gcc's a better model of the standard preprocessor here.
Since this is about the preprocessor I'm going to focus the story on just this snippet:
#define AA for, S
#define VALUE_TO_STRING(x) ^x!
#define VALUE(x) VALUE_TO_STRING(x)
VALUE(AA)
I'll be referencing ISO-14882 2011 here, which uses different numbers than 1998/2003. Using those numbers, here's what happens starting at the expansion step, step by step... except for steps not relevant here which I'll skip.
The preprocessor sees VALUE(AA), which is a function-like invocation of a previously defined function-like macro. So the first thing it does is argument identification, referencing 16.3 paragraph 4:
[if not variadic] the number of arguments (including those arguments consisting of no preprocessing tokens) in an invocation of a function-like macro shall equal the number of parameters in the macro definition
...and a portion of 16.3.1 paragraph 1:
After the arguments for the invocation of a function-like macro have been identified,
At this step, the preprocessor identifies that there is indeed one argument, that the macro was defined with one argument, and that the parameter x matches the invocation argument AA. So far, argument matching and x is AA is all that happened.
Then we get to the next step, which is argument expansion. With respect to this step, the only thing about the replacement list that really matters is where the parameters are in it, and whether or not the parameters are part of stringification (# x) or pasting (x ## ... or ... ## x). If there are arguments in the replacement list that are neither, then those arguments are expanded (stringified or pasted versions of the arguments don't count during this step). This expansion happens first, before anything else interesting goes on in the invocation, and it occurs just as if the preprocessor were only expanding the invocation parameter.
In this case, the replacement list is VALUE_TO_STRING(x). Again, VALUE_TO_STRING might be a function-like macro, but since we're doing argument expansion right now we really don't care. The only thing we care about is that x is there, and it's not being stringified or pasted. x is being invoked with AA, so the preprocessor evaluates AA as if AA were on a line instead of VALUE(AA). AA is an object-like macro that expands to for, S. So the replacement list transforms into VALUE_TO_STRING(for, S).
This is the rest of 16.3.1 paragraph 1 in action:
A parameter in the replacement list, unless [stringified or pasted] is replaced by the corresponding argument after all macros contained therein have been expanded [...] as if they formed the rest of the preprocessing file
So far so good. But now we reach the next part, in 16.3.4:
After all parameters in the replacement list have been substituted and [stuff not happening here] the resulting preprocessing token sequence
is rescanned, along with all subsequent preprocessing tokens of the source file, for more macro names to replace.
This part evaluates VALUE_TO_STRING(for, S), as if that were the preprocessing token set (except that it also temporarily forgets that VALUE is a macro per 16.3.4p2, but that doesn't come into play here). That evaluation recognizes VALUE_TO_STRING as a function-like macro, being invoked like one, so argument identification begins again. Only here, VALUE_TO_STRING was defined to take one argument, but is invoked with two. That fails 16.3 p 4.
I think the answer is in order of expanding.
Your simulation of preprocessor expanding, i.e. your choice of which macro to expand first, does in my opinion not match what the preprocessor does.
I, acting as a preprocessor (according to standard I believed at first; but a comment contradicts), would expand your code in this order:
VALUE(AA)
VALUE_TO_STRING(AA)
^AA!
^for, S!
This matches the result of the preprocessor for the original code.
Note that by this order it never sees the code VALUE_TO_STRING(for, S), the closest it gets is VALUE_TO_STRING(AA). That code does not cause the question concerning the number of arguments.
I did not quote anything from the standard, I think your quotes are sufficient.
As mentioned in a comment below, my answer is now an attempt how the result could be explained, without assuming conforming preprocessor. Any answer explaining with conforming behaviour is definitely better.
By the way, acting as a compiler, I would probably not understand the
^anything! as a way to make a string from a value either. But that is not the question and I assume that the meaning was lost, when you prepared the minimal example. That is of course perfectly allright. It might however influence the expansion, if it ever expands to a quoted macro name, e.g. "AA". That would stop expanding and the result could unveil what happened.
This question already has answers here:
Order of evaluation in C++ function parameters
(6 answers)
Closed 7 years ago.
I'm confused about in what order function arguments are evaluated when calling a C++ function. I have probably interepreted something wrong, so please explain if that is the case.
As an example, the legendary book "Programming Windows" by Charles Petzold contains code like this:
// hdc = handle to device context
// x, y = coordinates of where to output text
char szBuffer[64];
TextOut(hdc, x, y, szBuffer, snprintf(szBuffer, 64, "My text goes here"));
Now, the last argument is
snprintf(szBuffer, 64, "My text goes here")
which returns the number of characters written to the char[] szBuffer. It also writes the text "My text goes here" to the char[] szBuffer.
The fourth argument is szBuffer, which contains the text to be written. However, we can see that szBuffer is filled in the fifth argument, telling us that somehow is the expression
// argument 5
snprintf(szBuffer, 64, "My text goes here")
evaluated before
// argument 4
szBuffer
Okay, fine. Is this always the case? Evaluation is always done from right to left? Looking at the default calling convention __cdecl:
The main characteristics of __cdecl calling convention are:
Arguments are passed from right to left, and placed on the stack.
Stack cleanup is performed by the caller.
Function name is decorated by prefixing it with an underscore character '_' .
(Source: Calling conventions demystified)
(Source: MSDN on __cdecl)
It says "Arguments are passed from right to left, and placed on the stack".
Does this mean that the rightmost/last argument in a function call is always evaluated first? Then the next to last etc? The same goes for the calling convention __stdcall, it also specified a right-to-left argument passing order.
At the same time, I came across posts like this:
How are arguments evaluated in a function call?
In that post the answers say (and they're quoting the standard) that the order is unspecified.
Finally, when Charles Petzold writes
TextOut(hdc, x, y, szBuffer, snprintf(szBuffer, 64, "My text goes here"));
maybe it doesn't matter? Because even if
szBuffer
is evaluated before
snprintf(szBuffer, 64, "My text goes here")
the function TextOut is called with a char* (pointing to the first character in szBuffer), and since all arguments are evaluated before the TextOut function proceeds it doesn't matter in this particular case which gets evaluated first.
In this case it does not matter.
By passing szBuffer to a function that accepts a char * (or char const *) argument, the array decays to a pointer. The pointer value is independent of the actual data stored in the array, and the pointer value will be the same in both cases no matter whether the fourth or fifth argument to TextOut() gets fully evaluated first. Even if the fourth argument is fully evaluated first, it will evaluate as a pointer to data -- the pointed-to data is what gets changed, not the pointer itself.
To answer your posed question: the actual order of argument evaluation is unspecified. For example, in the statement f(g(), h()), a compliant compiler can execute g() and h() in any order. Further, in the statement f(g(h()), i()), the compiler can execute the three functions g, h, and i in any order with the constraint that h() gets executed before g() -- so it could execute h(), then i(), then g().
It just happens that in this specific case, evaluation order of arguments is wholly irrelevant.
(None of this behavior is dependent on calling convention, which only deals with how the arguments are communicated to the called function. The calling convention does not address in any way the order in which those arguments are evaluated.)
I would agree that it depends on the calling convention, because the standard does not specify the order.
See also: Compilers and argument order of evaluation in C++
And I would also agree that is does not matter in this case, because the snprintf is always evaluated before the TextOut - and the buffer gets filled.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
# and ## in macros
why the output of second printf is f(1,2) what is the order in which macro is evaluated?
#include <stdio.h>
#define f(a,b) a##b
#define g(a) #a
#define h(a) g(a)
int main()
{
printf("%s\n",h(f(1,2)));
printf("%s\n",g(f(1,2)));
return 0;
}
output 12
f(1,2)
From http://gcc.gnu.org/onlinedocs/cpp/Argument-Prescan.html#Argument-Prescan
Macro arguments are completely macro-expanded before they are substituted into a macro body, unless they are stringified or pasted with other tokens. After substitution, the entire macro body, including the substituted arguments, is scanned again for macros to be expanded. The result is that the arguments are scanned twice to expand macro calls in them.
Meaning:
f concatenates its argument and so its argument is not expanded
h does not stringify or concatenate its argument and so its argument is expanded.
g stringifies its argument, and so its argument is not expanded
h(f(1,2)) -> g(12) -> "12"
g(f(1,2)) -> "f(1,2)"
An argument is macro-replaced before it is substituted into the replacement list, except where it appears as the operand of # (stringize) or ## (concatenate).
In your macro h, the parameter a is not an argument of one of those two operators, so the argument is macro-replaced and then substitued into the replacement list. That is, the argument f(1,2) is macro replaced to become 1##2, and then to 12, and then it is substituted into g(12), which is (again) macro-replaced to become "12".
When you invoke g directly, the parameter a is an argument of the # operator, so its argument is not macro-replaced before subsitution: f(1,2) is substituted directly into the replacement list, yielding "f(1,2)".
I'm not sure order of evaluation is a meaningful term for C or C++ macros, because macro expansion happens at compile time
As to why the second output is f(1,2) is is because macros are textual substitution. When g(f(1,2)) is expanded, the argument of g is the sequence of tokens f(1,2) and that get stringified.
Think in terms of the C compiler. In the context of the second printf it reads a g token, recognize that it is a macro at lexing & parsing time then expand that macro invocation. The compiler is basically doing: if the current token is a macro name, then expand it when lexing your code. Macro expansion only happen when possible (so for a macro with arguments requires the left parenthesis), and is done as soon as possible.
At: C++ FAQ - Miscellaneous technical issues - [39.6] What should be done with macros that need to paste two tokens together?
Could someone explain to me why? All I read is trust me, but I simply can't just trust on something because someone said so.
I tried the approach and I can't find any bugs appearing:
#define mymacro(a) int a ## __LINE__
mymacro(prefix) = 5;
mymacro(__LINE__) = 5;
int test = prefix__LINE__*__LINE____LINE__; // fine
So why do I need to do it like this instead (quote from the webpage):
However you need a double layer of indirection when you use ##.
Basically you need to create a special macro for "token pasting" such
as:
#define NAME2(a,b) NAME2_HIDDEN(a,b)
#define NAME2_HIDDEN(a,b) a ## b
Trust me on this — you really need to do
this! (And please nobody write me saying it sometimes works without
the second layer of indirection. Try concatenating a symbol with
__ LINE__ and see what happens then.)
Edit: Could someone also explain why he uses NAME2_HIDDEN before it's declared below? It seems more logical to define NAME2_HIDDEN macro before I use it. Is it some sort of trick here?
The relevant part of the C spec:
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 ## 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 key part that determines whether you want the double indirection or not is the second sentence and the exception in it -- if the parameter is involved in a # or ## operation (such as the params in mymacro and NAME2_HIDDEN), then any other macros in the argument are NOT expanded prior to doing the # or ##. If, on the other hand, there's no # or ## IMMEDIATELY in the macro body (as with NAME2), then other macros in the parameters ARE expanded.
So it comes down to what you want -- sometimes you want all macros expanded FIRST, and then do the # or ## (in which case you want the double layer indirection) and sometime you DO NOT want the macros expanded first (in which case you CAN'T HAVE double layer macros, you need to do it directly.)
__LINE__ is a special macro that is supposed to resolve to the current line number. When you do a token paste with __LINE__ directly, however, it doesn't get a chance to resolve, so you end up with the token prefix__LINE__ instead of, say, prefix23, like you would probably be expecting if you would write this code in the wild.
Chris Dodd has an excellent explanation for the first part of your question. As for the second part, about the definition sequence, the short version is that #define directives by themselves are not evaluated at all; they are only evaluated and expanded when the symbol is found elsewhere in the file. For example:
#define A a //adds A->a to the symbol table
#define B b //adds B->b to the symbol table
int A;
#undef A //removes A->a from the symbol table
#define A B //adds A->B to the symbol table
int A;
The first int A; becomes int a; because that is how A is defined at that point in the file. The second int A; becomes int b; after two expansions. It is first expanded to int B; because A is defined as B at that point in the file. The preprocessor then recognizes that B is a macro when it checks the symbol table. B is then expanded to b.
The only thing that matters is the definition of the symbol at the point of expansion, regardless of where the definition is.
The most non-technical answer, which I gathered from all links here, and link of links ;) is that, a single layer indirection macro(x) #x stringifies the inputted macro's name, but by using double layers, it will stringify the inputted macro's value.
#define valueOfPi 3
#define macroHlp(x) #x
#define macro(x) macroHlp(x)
#define myVarOneLayer "Apprx. value of pi = " macroHlp(valueOfPi)
#define myVarTwoLayers "Apprx. value of pi = " macro(valueOfPi)
printf(myVarOneLayer); // out: Apprx. value of pi = valueOfPi
printf(myVarOTwoLayers); // out: Apprx. value of pi = 3
What happens at printf(myVarOneLayer)
printf(myVarOneLayer) is expanded to printf("Apprx. value of pi = " macroHlp(valueOfPi))
macroHlp(valueOfPi) tries to stringify the input, the input itself is not evaluated. It's only purpose in life is to take an input and stringify. So it expands to "valueOfPi"
So, what happens at printf(myVarTwoLayers)
printf(myVarTwoLayers) is expanded to printf("Apprx. value of pi = " macro(valueOfPi)
macro(valueOfPi) has no stringification operation, i.e. there is no #x in it's expansion, but there is an x, so it has to evaluate x and input the value to macroHlp for stringification. It expands to macroHlp(3) which in turn will stringify the number 3, since it is using #x
The order in which macros are declared is not important, the order in which they are used is. If you were to actually use that macro before it was declared -- (in actual code that is, not in a macro which remains dormant until summoned) then you would get an error of sorts but since most sane people don't go around doing these kinds of things, writing a macro and then writing a function that uses a macro not yet defined further down, etc,etc... It seems your question isn't just one question but I'll just answer that one part. I think you should have broken this down a little more.