Why does the compiler say this macro function needs a closing parenthesis? - c++

The code is below. The compiler says "Expected a )", but I do not get it: ( and ) are matching. What did I do wrong?
#define CR_SUCCESS 0
#define EXIT_IF_FAILS(varResult, callString) \
(\
varResult = callString; \
if(varResult != CR_SUCCESS) \
{ \
return -1; \
} \
)
int testFunction(int a, int b)
{
return -1;
}
int main()
{
int result;
EXIT_IF_FAILS(result, testFunction(1, 2));
}

Expanding, your main looks like
int main()
{
int result;
(
result = testFunction(1, 2);
if(result != CR_SUCCESS)
{
return -1;
}
)
}
This is invalid, since you cannot have parentheses around statements.
For some things you might do when you want a macro which acts like a statement, see the C++ FAQ "What should be done with macros that have multiple lines?"

You should, as a general rule, avoid function-like macros as much as possible, there's very little need to use them in modern C++(a). Most can be easily replaced with inline functions, or even non-inline functions if you trust the compiler to do the right thing.
I realise that's not appropriate for your specific use case since you need to exit the current function as part of the macro but I would ask you to think about why you think you need a macro for this case in the first place.
If it's to simply cut down on code lines, you can equally do that without a macro, such as with:
if ((result = testFunction(1, 2)) != CR_SUCCESS) return -1;
That's equally as succinct (in terms of line count) and doesn't require you to go looking for the macro definition to see what's actually happening.
It also doesn't need all the normal faffing about trying to make sure your macros work in all places where they may be used, such as needing to use the do { ... } while (0) trick to ensure it works inside if or else blocks without braces. See this question and its answers for more explanation on that point.
(a) In fact, even non-function-like macros may be better replaced with enumerations (at least those such as a set of mutually exclusive value like error codes). Nowadays, I tend to use #define only for conditional compilation, on those relatively rare occasions where I need it.

Related

Must a "is defined" macro check and its call be in separate conditions?

I was struggling to find an answer amoung many that refer to this topic on SO, but here's some seemingly innocent looking code that fails to compile when F is not a defined macro,
int main() {
#if defined(F) && F(0, 2, 0)
return 0;
#endif
return 1;
}
The problem, according to this section of the GCC manual is that inside #if expressions "all macros in the expression are expanded before actual computation of the expression’s value begins", so this in an invalid check, since when F is undefined, I see,
test.cpp:2:20: error: missing binary operator before token "("
#if defined(F) && F(0, 2, 0)
^
My question: is the only way to correctly do this check like so?
int main() {
#if defined(F)
#if F(0, 2, 0)
return 0;
#endif
#endif
return 1;
}
I find this quite ugly and unintuitive, so I'm hoping there's a nicer way to do such things in the preprocessor.
Assuming your F macro is defined in some header file, you could place the following code somewhere between the include and its first usage:
#ifndef F
#define F(a,b,c) 0
#endif
Or another reasonable default. That's a common solution for your problem. Another is to not allow such macros to be
not defined, but require either the default value or whatever it's expected to do. This latter approach is
a bit safer for e.g. configuration files, as it makes clear the author did consider the macro and intentionally
picked a value (i.e. he did not just forget to define it). It's also easier if the definition is in the same file.
Your test would then just be:
#if F(0, 2, 0)
Avoiding the nested condition (which would cause additional trouble if there was an #else required somewhere.
Two words of advise:
Use macros carefully and sparesely, only when reasonble. Expecially C++ provides features which reduce the need for macros.
Don't use single-letter names for macros. Remember they are textual replacements, bejond the normal language syntax. Use self-explanatory names instead (this does not only apply to macros, but for those it's even more relevant).

#define an array value with index

For Legacy reasons I need to maintain the old array structure(s), however the compiler tells me that there is a problem with my 'expression syntax'.
Here's what I have:
#define Array[GlobalIndexVariable] Get(GlobalIndexVariable)->SubType;
Get returns a valid pointer to a struct, which contains SubType
Now I imagined this to take every occasion of Array[GlobalIndexVariable] and simply convert it to the function call, but apparently I was mistaken.
I don't even really know what to search for in this context, so a little help would be highly appreciated.
Thank you very much.
Edit:
Since it was asked, here is one of the lines that throw the error:
LocalVariable = Array[GlobalIndexVariable];
I wish to stress, that I'm not looking to make this into a macro, but much rather just want to replace Array[GlobalIndexVariable]; with Get(GlobalIndexVariable), so as soon as anything other than GlobalIndexVariable is used, the replacement would fail and throw a different error.
Edit:
Just to make absolutely sure that I am understood:
Right now I have 4 long arrays of type int. I want to stuff these into a struct to both mark that they belong together (they describe different aspects of the same thing) however I need a bulk solution for the previous code fragments (a few thousand occurrences).
Old:
int Index = 2;
int Array1[ANZ] = { 0, 1, 2 };
int Array2[ANZ] = { 0, 1, 2 };
int Array3[ANZ] = { 0, 1, 2 };
int Array4[ANZ] = { 0, 1, 2 };
if(Array1[Index] == 2) //doSomething
New:
struct {
int Type, Conf, Foo, Bar;
};
if(Array1[Index] == 2) //doSomething
Without touching Array1[Index] == 2, is it possible to use a define or something else to get the exact same behavior as before for the old code?
With a custom type, you may do
struct MyType
{
int& operator[](int index) const { return Get(GlobalIndexVariable)->SubType; }
};
#define Array MyType{}
And then
Array[GlobalIndexVariable]
will be replaced by
MyType{}[GlobalIndexVariable]
which will calls
Get(GlobalIndexVariable)->SubType;
Your problem is in your #define
#define Array[GlobalIndexVariable] Get(GlobalIndexVariable)->SubType;
The [] isn't a valid syntax for macro calls. If you're doing C++ you can write an operator[] for your array type. If you're in C your in a bit of a bind. You'll probably have to replace everything with round brackets rather than square ones.
I'd perform a substitution, writing something like
#ifdef USE_OLD_SYNTAX
# define GET_ARRAY_VALUE(globalIndex) Array[globalIndex]
#else
# define GET_ARRAY_VALUE(globalIndex) Get(globalIndex)->SubType;
#endif
Then use GET_ARRAY_VALUE in your code and check with USE_OLD_SINTAX which definition you want to use by find-and-replace your previous code.
But maybe it can be more simple a find-and-replace inside your code without macro at all.

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.

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.

In which case is if(a=b) a good idea? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Inadvertent use of = instead of ==
C++ compilers let you know via warnings that you wrote,
if( a = b ) { //...
And that it might be a mistake that you certainly wanted to write:
if( a == b ) { //...
But is there a case where the warning should be ignored, because it's a good way to use this "feature"?
I don't see any code clarity reason possible, so is there a case where it’s useful?
Two possible reasons:
Assign & Check
The = operator (when not overriden) normally returns the value that it assigned. This is to allow statements such as a=b=c=3. In the context of your question, it also allows you to do something like this:
bool global;//a global variable
//a function
int foo(bool x){
//assign the value of x to global
//if x is equal to true, return 4
if (global=x)
return 4;
//otherwise return 3
return 3;
}
...which is equivalent to but shorter than:
bool global;//a global variable
//a function
int foo(bool x){
//assign the value of x to global
global=x;
//if x is equal to true, return 4
if (global==true)
return 4;
//otherwise return 3
return 3;
}
Also, it should be noted (as stated by Billy ONeal in a comment below) that this can also work when the left-hand argument of the = operator is actually a class with a conversion operator specified for a type which can be coerced (implicitly converted) to a bool. In other words, (a=b) will evaulate to true or false if a is of a type which can be coerced to a boolean value.
So the following is a similar situation to the above, except the left-hand argument to = is an object and not a bool:
#include <iostream>
using namespace std;
class Foo {
public:
operator bool (){ return true; }
Foo(){}
};
int main(){
Foo a;
Foo b;
if (a=b)
cout<<"true";
else
cout<<"false";
}
//output: true
Note: At the time of this writing, the code formatting above is bugged. My code (check the source) actually features proper indenting, shift operators and line spacing. The <'s are supposed to be <'s, and there aren't supposed to be enourmous gaps between each line.
Overridden = operator
Since C++ allows the overriding of operators, sometimes = will be overriden to do something other than what it does with primitive types. In these cases, the performing the = operation on an object could return a boolean (if that's how the = operator was overridden for that object type).
So the following code would perform the = operation on a with b as an argument. Then it would conditionally execute some code depending on the return value of that operation:
if (a=b){
//execute some code
}
Here, a would have to be an object and b would be of the correct type as defined by the overriding of the = operator for objects of a's type. To learn more about operator overriding, see this wikipedia article which includes C++ examples: Wikipedia article on operator overriding
while ( (line = readNextLine()) != EOF) {
processLine();
}
You could use to test if a function returned any error:
if (error_no = some_function(...)) {
// Handle error
}
Assuming that some_function returns the error code in case of an error. Or zero otherwise.
This is a consequence of basic feature of the C language:
The value of an assignment operation is the assigned value itself.
The fact that you can use that "return value" as the condition of an if() statement is incidental.
By the way, this is the same trick that allows this crazy conciseness:
void strcpy(char *s, char *t)
{
while( *s++ = *t++ );
}
Of course, the while exits when the nullchar in t is reached, but at the same time it is copied to the destination s string.
Whether it is a good idea, usually not, as it reduce code readability and is prone to errors.
Although the construct is perfectly legal syntax and your intent may truly be as shown below, don't leave the "!= 0" part out.
if( (a = b) != 0 ) {
...
}
The person looking at the code 6 months, 1 year, 5 years from now, at first glance, is simply going to believe the code contains a "classic bug" written by a junior programmer and will try to "fix" it. The construct above clearly indicates your intent and will be optimized out by the compiler. This would be especially embarrassing if you are that person.
Your other option is to heavily load it with comments. But the above is self-documenting code, which is better.
Lastly, my preference is to do this:
a = b;
if( a != 0 ) {
...
}
This is about a clear as the code can get. If there is a performance hit, it is virtually zero.
A common example where it is useful might be:
do {
...
} while (current = current->next);
I know that with this syntax you can avoid putting an extra line in your code, but I think it takes away some readability from the code.
This syntax is very useful for things like the one suggested by Steven Schlansker, but using it directly as a condition isn't a good idea.
This isn't actually a deliberate feature of C, but a consequence of two other features:
Assignment returns the assigned value
This is useful for performing multiple assignments, like a = b = 0, or loops like while ((n = getchar()) != EOF).
Numbers and pointers have truth values
C originally didn't have a bool type until the 1999 standard, so it used int to represent Boolean values. Backwards compatibility requires C and C++ to allow non-bool expressions in if, while, and for.
So, if a = b has a value and if is lenient about what values it accepts, then if (a = b) works. But I'd recommend using if ((a = b) != 0) instead to discourage anyone from "fixing" it.
You should explicitly write the checking statement in a better coding manner, avoiding the assign & check approach. Example:
if ((fp = fopen("filename.txt", "wt")) != NULL) {
// Do something with fp
}
void some( int b ) {
int a = 0;
if( a = b ) {
// or do something with a
// knowing that is not 0
}
// b remains the same
}
But is there a case where the warning
should be ignored because it's a good
way to use this "feature"? I don't see
any code clarity reason possible so is
there a case where its useful?
The warning can be suppressed by placing an extra parentheses around the assignment. That sort of clarifies the programmer's intent. Common cases I've seen that would match the (a = b) case directly would be something like:
if ( (a = expression_with_zero_for_failure) )
{
// do something with 'a' to avoid having to reevaluate
// 'expression_with_zero_for_failure' (might be a function call, e.g.)
}
else if ( (a = expression2_with_zero_for_failure) )
{
// do something with 'a' to avoid having to reevaluate
// 'expression2_with_zero_for_failure'
}
// etc.
As to whether writing this kind of code is useful enough to justify the common mistakes that beginners (and sometimes even professionals in their worst moments) encounter when using C++, it's difficult to say. It's a legacy inherited from C and Stroustrup and others contributing to the design of C++ might have gone a completely different, safer route had they not tried to make C++ backwards compatible with C as much as possible.
Personally I think it's not worth it. I work in a team and I've encountered this bug several times before. I would have been in favor of disallowing it (requiring parentheses or some other explicit syntax at least or else it's considered a build error) in exchange for lifting the burden of ever encountering these bugs.
while( (l = getline()) != EOF){
printf("%s\n", l);
}
This is of course the simplest example, and there are lots of times when this is useful. The primary thing to remember is that (a = true) returns true, just as (a = false) returns false.
Preamble
Note that this answer is about C++ (I started writing this answer before the tag "C" was added).
Still, after reading Jens Gustedt's comment, I realized it was not the first time I wrote this kind of answer. Truth is, this question is a duplicate of another, to which I gave the following answer:
Inadvertent use of = instead of ==
So, I'll shamelessly quote myself here to add an important information: if is not about comparison. It's about evaluation.
This difference is very important, because it means anything can be inside the parentheses of a if as long as it can be evaluated to a Boolean. And this is a good thing.
Now, limiting the language by forbidding =, where all other operators are authorized, is a dangerous exception for the language, an exception whose use would be far from certain, and whose drawbacks would be numerous indeed.
For those who are uneasy with the = typo, then there are solutions (see Alternatives below...).
About the valid uses of if(i = 0) [Quoted from myself]
The problem is that you're taking the problem upside down. The "if" notation is not about comparing two values like in some other languages.
The C/C++ if instruction waits for any expression that will evaluate to either a Boolean, or a null/non-null value. This expression can include two values comparison, and/or can be much more complex.
For example, you can have:
if(i >> 3)
{
std::cout << "i is less than 8" << std::endl
}
Which proves that, in C/C++, the if expression is not limited to == and =. Anything will do, as long as it can be evaluated as true or false (C++), or zero non-zero (C/C++).
About valid uses
Back to the non-quoted answer.
The following notation:
if(MyObject * p = findMyObject())
{
// uses p
}
enables the user to declare and then use p inside the if. It is a syntactic sugar... But an interesting one. For example, imagine the case of an XML DOM-like object whose type is unknown well until runtime, and you need to use RTTI:
void foo(Node * p_p)
{
if(BodyNode * p = dynamic_cast<BodyNode *>(p_p))
{
// this is a <body> node
}
else if(SpanNode * p = dynamic_cast<SpanNode *>(p_p))
{
// this is a <span> node
}
else if(DivNode * p = dynamic_cast<DivNode *>(p_p))
{
// this is a <div> node
}
// etc.
}
RTTI should not be abused, of course, but this is but one example of this syntactic sugar.
Another use would be to use what is called C++ variable injection. In Java, there is this cool keyword:
synchronized(p)
{
// Now, the Java code is synchronized using p as a mutex
}
In C++, you can do it, too. I don't have the exact code in mind (nor the exact Dr. Dobb's Journal's article where I discovered it), but this simple define should be enough for demonstration purposes:
#define synchronized(lock) \
if (auto_lock lock_##__LINE__(lock))
synchronized(p)
{
// Now, the C++ code is synchronized using p as a mutex
}
(Note that this macro is quite primitive, and should not be used as is in production code. The real macro uses a if and a for. See sources below for a more correct implementation).
This is the same way, mixing injection with if and for declaration, you can declare a primitive foreach macro (if you want an industrial-strength foreach, use Boost's).
About your typo problem
Your problem is a typo, and there are multiple ways to limit its frequency in your code. The most important one is to make sure the left-hand-side operand is constant.
For example, this code won't compile for multiple reasons:
if( NULL = b ) // won't compile because it is illegal
// to assign a value to r-values.
Or even better:
const T a ;
// etc.
if( a = b ) // Won't compile because it is illegal
// to modify a constant object
This is why in my code, const is one of the most used keyword you'll find. Unless I really want to modify a variable, it is declared const and thus, the compiler protects me from most errors, including the typo error that motivated you to write this question.
But is there a case where the warning should be ignored because it's a good way to use this "feature"? I don't see any code clarity reason possible so is there a case where its useful?
Conclusion
As shown in the examples above, there are multiple valid uses for the feature you used in your question.
My own code is a magnitude cleaner and clearer since I use the code injection enabled by this feature:
void foo()
{
// some code
LOCK(mutex)
{
// some code protected by a mutex
}
FOREACH(char c, MyVectorOfChar)
{
// using 'c'
}
}
... which makes the rare times I was confronted to this typo a negligible price to pay (and I can't remember the last time I wrote this type without being caught by the compiler).
Interesting sources
I finally found the articles I've had read on variable injection. Here we go!!!
FOR_EACH and LOCK (2003-11-01)
Exception Safety Analysis (2003-12-01)
Concurrent Access Control & C++ (2004-01-01)
Alternatives
If one fears being victim of the =/== typo, then perhaps using a macro could help:
#define EQUALS ==
#define ARE_EQUALS(lhs,rhs) (lhs == rhs)
int main(int argc, char* argv[])
{
int a = 25 ;
double b = 25 ;
if(a EQUALS b)
std::cout << "equals" << std::endl ;
else
std::cout << "NOT equals" << std::endl ;
if(ARE_EQUALS(a, b))
std::cout << "equals" << std::endl ;
else
std::cout << "NOT equals" << std::endl ;
return 0 ;
}
This way, one can protect oneself from the typo error, without needing a language limitation (that would cripple language), for a bug that happens rarely (i.e., almost never, as far as I remember it in my code).
There's an aspect of this that hasn't been mentioned: C doesn't prevent you from doing anything it doesn't have to. It doesn't prevent you from doing it because C's job is to give you enough rope to hang yourself by. To not think that it's smarter than you. And it's good at it.
Never!
The exceptions cited don't generate the compiler warning. In cases where the compiler generates the warning, it is never a good idea.
RegEx sample
RegEx r;
if(((r = new RegEx("\w*)).IsMatch()) {
// ... do something here
}
else if((r = new RegEx("\d*")).IsMatch()) {
// ... do something here
}
Assign a value test
int i = 0;
if((i = 1) == 1) {
// 1 is equal to i that was assigned to a int value 1
}
else {
// ?
}
My favourite is:
if (CComQIPtr<DerivedClassA> a = BaseClassPtr)
{
...
}
else if (CComQIPtr<DerivedClassB> b = BaseClassPtr)
{
...
}