Usage of macro in C language - c++

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

Related

Declaring a function using #define

I came across a c++ code where a function was defined in the header section of the file as follows
#define APPEND_VALUE(X, Y, I)\
{\
int idx = (Y*100+X);\
int idxn = idx + ValueCount[idx];\
TempVector[idxn] = I;\
CountVector[idx] += 1;\
}
(Note that this is not all the code and TempVector and CountVector was defined elsewhere)
Later in the code APPEND_VALUE was used like any other function. I was wondering what is the difference between the above (#define APPEND_VALUE) code and the below code
void APPEND_VALUE(int X, int Y, int I)
{
int idx = (Y*100+X);
int idxn = idx + ValueCount[idx];
TempVector[idxn] = I;
CountVector[idx] += 1;
}
What is the advantage of using one over the other? also is there a technical name for defining a function as show in the first code(the one using #define).
#define is part of something called the "preprocessor." Essentially, this is the code that is processed before the C document is compiled. Most of the preprocessor code is in a file with a ".h" extension (which is why you may have seen that when importing libraries).
The preprocessor language is primitive. For example, if it performs a "textual substitution [with] missing parentheses", the result of the preprocessor function may not be what you intended it to return (credit: #Deduplicator). Take a look at this post for an example: #define Square(x) (x*(x)). For this reason, and many others, I would prefer coding it in the regular C language when possible (just note there are many cases where the preprocessor may be faster and more helpful). Hope this helps!

can #define be used for printing information?

I came across a statement which I didn’t understand. Can anyone explain me please.
It is a C++ program to sort data.
#define PRINT(DATA,N) for(int i=0; i<N; i++) { cout<<"["<<i<<"]"<<DATA[i]<<endl; } cout<<endl;
And also when I tried to rearrange the statement in the below format,I got compilation error!
#define PRINT(DATA,N)
for(int i=0; i<N; i++)
{
cout<<"["<<i<<"]"<<DATA[i]<<endl;
}
cout<<endl;
It's a macro, each time you write PRINT(DATA,N) the pre-processor will substitute it for the entire for loop, including the variables.
You're missing \ signs at the end of each line. This tells it the Macro continues to the next line. (Look at Multi-statement Macros in C++
If you use macro, use brackets around any variables (DATA) and (N). The substitution is literal and this will allow usages like PRINT(data, x+1) which otherwise cause unexpected results.
Don't use macro unless you REALLY must, there are many problems that can arise from this, it doesn't have a scope and so on. You can write an inline method or use std::copy_n like Nawaz proposed
It can be used if you properly define it. But .... just because it can be used, does not mean that it should be used.
Use std::copy_n:
std::copy_n(data, n, std::stream_iterator<X>(std::cout, " "));
That will print all the n items from data to the stdout, each separated by a space. Note that in the above code, X is the type of data[i].
Or write a proper function (not macro) to print in your own defined format. Preferably a function template with begin and end as function parameters. Have a look at how algorithms from the Standard library work and are implemented. That will help you to come up with a good generic design of your code. Explore and experiment with the library generic functions!
This isn't something you want to use a macro for.
Write a template function that does the exact same thing:
template<typename T>
void PRINT(const T &data, size_t n){
for (size_t i=0;i<n;++i)
cout << "["<<i<<"]"<<data[i]<<endl;
}
You should really avoid using macros. The only reason I find you NEED macros is when you need to use the name of the input (as string), or location (LINE or FILE) e.g.:
#define OUT(x) #x<<"="<<x<<"; "
#define DEB std::cerr<<"In "<<__FILE__<<":"<<__LINE__<<": "
for use in printing like this:
DEB << OUT(i)<<OUT(val[i])<<OUT(some_func(val[i],3))<<endl;
Which will print
In file.cc:153: i=4; val[i]=10; some_func(val[i],3)=4.32;
This is a functionality you can't do without macros. Anything you CAN do without macros you SHOULD

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

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

Should I avoid using #define in C++? Why, and what alternatives can I use?

For some kinds of programs I need to use a constant high value to indicate some properties of some variables. I mean let color[i] = 1000000; if the i node in a tree is unexplored. But I quite often miswrite the number of 0s at the end, so I just wondered whether is it better to do it this way:
#define UNEXPLORED 1000000;
color[i] = UNEXPLORED;
I remember that somewhere I have read that it's much better to avoid using #define. Is it right? How would you tackle this problem?
For simple constants, you can use either const or the new constexpr:
constexpr unsigned int UNEXPLORED = 1000000;
In a case like this, it's no difference between using const and constexpr. However, "variables" marked constexpr are evaluated at compile-time and not at run-time, and may be used in places that otherwise only accepts literals.
For example use constants.
const unsigned int UNEXPLORED = 1000000;
or enums
enum { UNEXPLORED = 1000000 };
In the use of constants the two answers above are correct, however #define is not limited to that use alone. Another example of the use of #define is macros.
Macros
Macros are preprocessor-utilised pieces of code, and they work exactly like other #define declarations in that regard. The preprocessor will literally swap out the occurrence of your defined symbol with the code of the macro. An example:
#define HELLO_MAC do{ std::cout << "Hello World" << std::endl; }while(false)
int main(int argc, char** argv)
{
HELLO_MAC;
}
That will literally swap out the HELLO_MAC symbol with the code I declared. If it were a constant it would do the exact same thing. So you can think of #defines for constants as a particular kind of macro.
With macros you can also pass parameters, and it is especially useful I find for enforcing logging/exception policies over code.
For example
#define THROW_EXCEPT( ex_type, ex_msg ) /
do{ throw ex_type( buildExString( (ex_msg), __LINE__, __FILE__ ) ); }while(false)
...
// somewhere else
THROW_EXCEPT( std::runtime_error, "Unsupported operation in current state" );
That code allows me to ensure that everyone logs with the line of the file that threw the exception.
Templates are often a better choice instead of macros, but I cannot use template functions for this example because I need to use the __LINE__ and __FILE__ functions from the place of the throw, not from the location of the template function.
Where should you not use macros? Anywhere you can use something else. Macros, like any #define are preprocessed, so the compiler does not see them at all. This means that there is never any symbols created for HELLO_MAC or THROW_EXCEPT, and so they cannot be seen in a debugger. They can also be confusing if you get compile errors, especially if they are long macros.

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.