c++ #define and concatenate case (I am using gcc) - c++

I have
#define NAME(value) my ## value ## value
when I do NAME(1), it is my1value, which is good!
But I want to pass variable into NAME(),
such as
for(int i=0;i<10;i++)
{
NAME(i);
...
}
But unfortunately, it becomes myivalue, but I want my0value, my1value etc.
What should I change?
Thanks

Macros are substituted at compile-time (actually, they are substituted by the preprocessr even before "real" compilation begins), and it's pure text processing.
You cannot expect your macro to compute its expansion based on the value of a variable.

Macros only do text-replacement before compiling. It's basically the same as doing a 'Find&Replace' over your code. Loops are executed at runtime - so this doesn't make any sense.
But to answer your question anyway .... you could use a (compile-time) macro 'loop':
#include <iostream>
#define NAME(v) my##v##value
#define LOOP10 NAME(0), NAME(1), NAME(2), NAME(3), NAME(4), NAME(5), NAME(6), NAME(7), NAME(8), NAME(9)
int main()
{
int LOOP10; // example usage
}
boost supports preprocessor loops, as far as I know.

## is a pre-processor directive
## concatenates what's before the ## with what's after it in the #define statement
As u said "#define NAME(value) my ## value ## value" this becomes an error.it means "myii" not myivalue

Related

Can you feed a macro to another macro as an argument, without the initial macro being expanded?

Background: My code, which I cannot post here will eventually run on a microcontroller, and the macros just offer a way to create multiple pin definition functions, via 1 single macro define mechanic. I use windows and gcc to experiment around with those.
I tried to abstract the problem as much as possible. I use the std console functions cause it is convenient for me to display it in the console window. As such, I also save the file as .cpp and compile it with g++ on windows.
Say I set up my code like this:
#define MACRO2(_x) foo##_x(_x)
#define MACRO1(_x) MACRO2(_x)
#define BAR 3
void fooBAR(int num)
{
std::cout << num << std::endl;
}
If I run the following code (working example)
int main()
{
MACRO2(BAR);
return 0;
}
first BAR gets inserted into ##_x and thus defines the function name which is to be called and then BAR gets inserted as the argument of that function and gets expanded to its value, so we get fooBAR(3). The code works, there are no errors.
Now if I try to add a macro in between (and this is the real world situation I am faced with for reasons I cannot go into), my code looks like this:
int main()
{
MACRO1(BAR);
return 0;
}
But this code throws an error, because when MACRO1(BAR) gets substituted with MACRO2(BAR), (BAR) then gets expanded into 3, and MACRO2(3) leads to foo3(3) which isn't defined, as confirmed by the error log:
error: 'foo3' was not declared in this scope
So the requirements are:
I need to pass BAR into MACRO1 and it needs to be passed to MACRO2 without being expanded
The word BAR has to stay exactly as it is, I know I could use ## in order to prevent it from expanding, but then I would need to add a char to BAR and the function call wouldn't work anymore.
Is it possible to somehow get this done? Pass a macro to another macro as an argument, without the initial macro being expanded in the process?
But this code throws an error, because when MACRO1(BAR) gets
substituted with MACRO2(BAR), (BAR) then gets expanded into 3, and
MACRO2(3) leads to foo3(3)
Yes. This is the specified preprocessor behavior for your particular set of macros.
After they are identified, the arguments to a function-like macro are fully macro-expanded before being substituted into the macro's replacement text, except where they are operands of the ## or # preprocessor operator. Any appearances of those operators are evaluated, and then the resulting text is rescanned, along with any following text as appropriate, for additional macros to expand.
Is it possible to somehow get this done? Pass a macro to another macro as an argument, without the initial macro being expanded in the process?
Only where the argument is the operand of a ## or # operator. The latter doesn't help you, but the former affords a workaround: you can pass an additional, empty argument so that you can perform a concatenation without changing the wanted argument:
#define MACRO2(_x) foo##_x(_x)
#define MACRO1(_x,dummy) MACRO2(_x##dummy)
#define BAR 3
int main()
{
MACRO1(BAR,);
return 0;
}
That expands to
int main()
{
fooBAR(3);
return 0;
}
If you want to avoid the extra comma, then you can do so by making MACRO1 variadic:
#define MACRO2(_x) foo##_x(_x)
#define MACRO1(_x,...) MACRO2(_x##__VA_ARGS__)
#define BAR 3
int main()
{
MACRO1(BAR);
return 0;
}
That expands to the same thing as the other.
Do note that both of these approaches afford the possibility of an error being introduced by providing unwanted extra argument values to the top-level macro. One would probably suppose that most such errors would be caught at compile time, as the expansion would result in broken code, like the attempt in the question. But it is hard to rule out the possibility that such an error would coincidentally expand to something that happened to be valid, but wrong.
One way to accomplish this is to change slightly the definition of BAR.
#define MACRO2(_x) foo##_x(_x())
#define MACRO1(_x) MACRO2(_x)
#define BAR() 3

When and why use a #define macro(x) instead of function?

Seeing this question made me wonder why the approach (toy example):
#define foo(x) bar[x] = 0
would ever be preferred over the function:
void foo(unsigned x){ bar[x] = 0; }
Before the question linked above, I've only seen this once before, in the PolarSSL library, where I assumed it to be some sort of optimisation, and tried not to think too much about it.
I assume that using the preprocessor macro replaces the 'call' to be the '(not-) function body' everywhere it exists; whereas the void function may or may not be optimised out by the compiler, and therefore may result in a lot of branching for a small and simple operation or two.
Is there any other benefit?
When is the macro method preferred, and when is it better to trust the compiler?
Firstly, I'd hope your macro was actually:
#define foo(x) do { bar[x] = 0; } while (0)
for proper semicolon swallowing.
One thing in favour of macros is because you think your compiler's optimiser is not good enough. You're probably wrong. But if you've actually looked at the output carefully and know what you are doing, you might be right, which is why it's often used in the Linux kernel.
Another reason is that macros are typeless, so you might do:
#define foo(x,t) do { t[x] = 0; } while (0)
which will work for any type t. Lack of type checking is often a disadvantage, but it can be useful when defining something you want to work with any type.
Defining macro just to make the code faster is useless. A good compiler will inline
function call. However, macros can be useful when you need to use their result as constant.
#define ENCODED(a,b,c,d) (((((((a)<<8)+b)<<8)+c)<<8)+d)
switch (a) {
case ENCODED('f','o','o','0'): ...
case ENCODED('b', 'a', 'r', '1'): ...
}
When you want to define new identifiers:
#define LIB_VERSION v101
#define VERSIONNED(x) x##LIB_VERSION
void VERSIONNED(myfunction)(int x) { ... }
When you want to do some other "magics",. For example:
#define assert(x) {if ((x) == 0) {printf("%s:%d: Assertion %s failed\n", __FILE__, __LINE__, #x); exit(-1); }}
When you want to define a "generic" function working with several types. Just for illustration:
#define DELETE_LAST_ITEM(x) {while (x->next->next != NULL) x=x->next ; x->next = NULL}
and probably some other situations which I do not remember right now.
Is there any other benefit?
There are few situational benefits of using macro. Just for an example, you may use __LINE__ and __FILE__ to see where this macro is getting called for debugging.
#define foo(x) bar[x] = 0; PrintFunction("...", __FILE__,__LINE__)
The macro would never give you stronger type checking like function.
When is the macro method preferred, and when is it better to trust the compiler?
Hence, Macro should be preferred only when you don't have any choice left to use a function, because most of the times you may trust the compiler optimizer.

Usage of macro in C language

I need to concatenate strings using macros to generate function names.
#define CONCAT(a,b,c) a ## b
int i=1;
CONCAT(a,i)
This code gives ai as a result, while what I wanted is a1.
As there are many functions in my source code, I don't want to enumerate them.
My goal:
for(int i=0;i<100;i++)
{
Funi1();//here i should be from 0 to one hundred
Funi2();
Funi3();
Funi4();
..
}
#Potatoswatter
I have written a script to expand it and the output file cost serval hundred lines.
#Eric Finn
It is not possible since macros are expanded during pre-processing stage.
So, it can not take the value of a variable and concat.
what about __COUNTER__ predefined macro, you have it on GCC and VC. Does it help you?
#include <stdio.h>
#define FUNC2(x,y) x##y
#define FUNC1(x,y) FUNC2(x,y)
#define FUNC(x) FUNC1(x,__COUNTER__)
int FUNC(my_unique_prefix);
int FUNC(my_unique_prefix);
int main() {
my_unique_prefix0 = 0;
printf_s("\n%d",my_unique_prefix0);
my_unique_prefix0++;
printf_s("\n%d",my_unique_prefix0);
}
Example from here
you can pre-compile it with: gcc -E sourcecode.c and watch it, it just replace variable name, and not get value and calculate at all, so it's not possible to let it works like you want.
try it with the LINE macro, it gives u numbers :) if u dont care about 1+1+1+1
like
static int FUNCADD(once,LINE)=1;if(FUNCADD(once,LINE)>0)
if that worx for u

preprocessor directive in while condition not working

when trying to use a variable defined in a preprocessor directive:
#define TIME_CONST 20;
in a while condition:
while(i<TIME_CONST){...}
I get an error complaining about parantheses...
when i use:
while(i<20)
everything works fine.
what am I doing wrong?
Thank you in advance!
#define TIME_CONST 20;
Remove ; from the end.
Because of ;, the following:
while(i<TIME_CONST){...}
becomes this:
while(i< 20;){...}
which is wrong, isn't it?
In C++ (and C), macros are text-replacement mechanism, so any usage of TIME_CONST will be replaced by 20; because that is how it has been defined.
An advice: avoid macro as much as possible . You've better alternative in C++. Use const (or constexpr ) to define your really constant object:
const int TIME_CONST = 20;
Now ; is fine, infact required by the language.

How to merge symbol name and symbol value in C preprocessor

The idea is to create automatic caster which would paste pointer to the variable based on given prefix and number.
Lets say you have some interface which is continously developed so you get some new structure versions every couple of weeks. So instead of writing explicity "(structure1*), (structure2*)" and so on you could just use SOME_DEFINE(thisStructure, version); which would handle the case
I thought that this would do the trick
#define d1(x) x
#define d2(x,y) x##y
void someFunction()
{
int temp = 3;
d2(myStructure,d1(temp)) *thisStruct;
}
i was hoping that preprocessor would nest itself and paste d1 operation first and then merge result of d1 operation with first d2 argument. However it doesnt work, so my question is, how can i achive this cause it seems to be possible.
I'm not sure exactly what you're trying to do, but the usual problem
here is that the preprocessor does token pasting and stringization
before it does macro replacement within its arguments. So if you write
something like:
#define PASTE(a,b) a ## b
and call it:
#define x 123
PASTE(A,x)
, the last line expands to Ax, and not to A123. To get the desired
results, it is often necessary to add a level of indirection:
#define PASTEHELPER(a,b) a ## b
#define PASTE(a,b) PASTEHELPER(a,b)
This works because full macro expansion of the arguments to PASTE will
take place before PASTEHELPER is expanded, so in PASTE(A,x), above,
the arguments to PASTEHELPER will be A and 123.
#define d2(x,y) x ## y
void someFunction()
{
int temp = 3;
d2(myStructure,temp) *thisStruct;
}
The preprocessor converts this to:
void someFunction()
{
int temp = 3;
myStructuretemp *thisStruct;
}
If you want to replace the '3' in there so you get myStructure3, then you cannot do that with the preprocessor - it doesn't know anything about C/C++ variables or their values.