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!
Related
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
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.
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.
Is there any way (such as compiler flag) to set ALL local variables const automatically without the specifier in C/C++/Objective-C? Just like let semantics in functional languages.
Because I want to set const to all local variables, but it's too annoying and makes code less readable. If I can set all local variables const by default, and I can set some variables mutable manually, it would be great for me. But I never heard about it.
If you know something please let me know.
Edit
I thought a little more about this after reading responses. And I strongly agree to it would disrupt strong C convention (or standard?) because it's already defined as mutable by default.
So my idea is becoming into another form. Kind of static analyzer. Not compiler.
if some tool can check reassigned local variables, and can define any mechanism marking mutable variable (for example, a specific empty preprocessor symbol), it would be perfect tool for me. And also, it won't disrupt C conventions.
So I changed question title a little and added this text.
... errr sort of by employing macros:
int main () {
#define int const int
#define float const float
int x = 5;
float y = 5.3;
#undef int
#undef float
return 0;
}
you can even separate these def's and undef's into two different headers, so that your code would look a bit cleaner:
int main () {
#include "all_vars_const_begin.h"
int x = 5;
float y = 5.3;
#include "all_vars_const_end.h"
return 0;
}
But i'm not sure if this style is Ok.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When are C++ macros beneficial?
Why is #define bad and what is the proper substitute?
Someone has told me that #define is bad. Well, I honestly don't not understand why its bad. If its bad, then what other way can I do this then?
#include <iostream>
#define stop() cin.ignore(numeric_limits<streamsize>::max(), '\n');
#define is not inherently bad. However, there are usually better ways of doing what you want. Consider an inline function:
inline void stop() {
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
(Really, you don't even need inline for a function like that. Just a plain ordinary function would work just fine.)
It's bad because it's indiscriminate. Anywhere you have stop() in your code will get replaced.
The way you solve it is by putting that code into its own method.
In C++, using #define is not forcibly bad, although alternatives should be preferred. There are some context, such as include guards in which there is no other portable/standard alternative.
It should be avoided because the C preprocessor operates (as the name suggests) before the compiler. It performs simple textual replacement, without regard to other definitions. This means the result input to the compiler sometimes doesn't make sense. Consider:
// in some header file.
#define FOO 5
// in some source file.
int main ()
{
// pre-compiles to: "int 5 = 2;"
// the compiler will vomit a weird compiler error.
int FOO = 2;
}
This example may seem trivial, but real examples exist. Some Windows SDK headers define:
#define min(a,b) ((a<b)?(a):(b))
And then code like:
#include <Windows.h>
#include <algorithm>
int main ()
{
// pre-compiles to: "int i = std::((1<2)?(1):(2));"
// the compiler will vomit a weird compiler error.
int i = std::min(1, 2);
}
When there are alternatives, use them. In the posted example, you can easily write:
void stop() {
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
For constants, use real C++ constants:
// instead of
#define FOO 5
// prefer
static const int FOO = 5;
This will guarantee that your compiler sees the same thing you do and benefit you with name overrides in nested scopes (a local FOO variable will override the meaning of global FOO) as expected.
It's not necessarily bad, it's just that most things people have used it for in the past can be done in a much better way.
For example, that snippet you provide (and other code macros) could be an inline function, something like (untested):
static inline void stop (void) {
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
In addition, there are all the other things that code macros force you to do "macro gymnastics" for, such as if you wanted to call the very badly written:
#define f(x) x * x * x + x
with:
int y = f (a + 1); // a + 1 * a + 1 * a + 1 + a + 1 (4a+2, not a^3+a)
int z = f (a++); // a++ * a++ * a++ + a++
The first of those will totally surprise you with its results due to the precedence of operators, and the second will give you undefined behaviour. Inline functions do not suffer these problems.
The other major thing that macros are used for is for providing enumerated values such as:
#define ERR_OK 0
#define ERR_ARG 1
: :
#define ERR_MEM 99
and these are better done with enumerations.
The main problem with macros is that the substitution is done early in the translation phase, and information is often lost because of this. For example, a debugger generally doesn't know about ERR_ARG since it would have been substituted long before the part of the translation process that creates debugging information.
But, having maligned them enough, they're still useful for defining simple variables which can be used for conditional compilation. That's pretty much all I use them for in C++ nowadays.
#define by itself is not bad, but it does have some bad properties to it. I'll list a few things that I know of:
"Functions" do not act as expected.
The following code seems reasonable:
#define getmax(a,b) (a > b ? a : b)
...but what happens if I call it as such?:
int a = 5;
int b = 2;
int c = getmax(++a,b); // c equals 7.
No, that is not a typo. c will be equal to 7. If you don't believe me, try it. That alone should be enough to scare you.
The preprocessor is inherently global
Whenever you use a #define to define a function (such as stop()), it acts across ALL included files after being discovered.
What this means is that you can actually change libraries that you did not write. As long as they use the function stop() in the header file, you could change the behavior of code you didn't write and didn't modify.
Debugging is more difficult.
The preprocessor does symbolic replacement before the code ever makes it to the compiler. Thus if you have the following code:
#define NUM_CUSTOMERS 10
#define PRICE_PER_CUSTOMER 1.10
...
double something = NUM_CUSTOMERS * PRICE_PER_CUSTOMER;
if there is an error on that line, then you will NOT see the convenient variable names in the error message, but rather will see something like this:
double something = 10 * 1.10;
So that makes it more difficult to find things in code. In this example, it doesn't seem that bad, but if you really get into the habit of doing it, then you can run into some real headaches.