C preprocessor with if statement - macros

I have the following macro:
#define IF_TRACE_ENABLED(level) if (IsTraceEnabled(level))
The user code should look following:
IF_TRACE_ENABLED(LEVEL1)
{
... some very smart code
}
The emphasis here on curly brackets - I want to prevent "if" from macro to "eat" other code:
if (...)
IF_TRACE_ENABLED(LEVEL1)
printf(....);
else
bla bla bla
In this example IF_TRACE_ENABLED "eats" else block.
Is there way to enforce user code not compile without curly brakes or there are other to define the macro to achieve the safety?

This doesn't force the user of the macro to use braces, but it will prevent an else clause from being unintentionally eaten:
#define IF_TRACE_ENABLED(level) if (!IsTraceEnabled(level)) {} else
A side note: braces around the printf() in the second example of the question wouldn't have fixed the problem - the else associated with bla bla bla would still be bound to the if statement in the macro.

You could try this:
#define IF_TRACE_ENABLED(level) do { if(IsTraceEnabled(level)) {
#define END_TRACE_ENABLED } } while(0);
I don't think there's any way to "enforce" good syntax from only the opening line of the macro. You will need to use two.
EDIT
I've added an extra pair of braces inside the macro to avoid all ambiguity.
In response to the comment, this macro is meant to be used like this:
IF_TRACE_ENABLED(LEVEL1)
printf("Trace\n");
END_TRACE_ENABLED
Not as a statement. For the record, I think this is an abuse of the preprocessor and nobody should do this at all. What's wrong with just writing it out, bracketed with #ifdef DEBUG if necessary.

This should work, but you'll have the pass the contents of the if block as an argument to the macro as well:
#define IF_TRACE_ENABLED(level,content) { if (IsTraceEnabled(level)) {content} }

Related

Comments on scalastyle:ignore

When I tell scalastyle to ignore a line, I would like to put a comment in the code explaining to future developers why that line deserves exemption from the normal rules.
I can obviously put it in the previous line, like:
// might be called from java code
if (foo == null) { // scalastyle:ignore
...
}
But ideally, I would like it in-line, like:
if (foo == null) { // scalastyle:ignore : Might be called from java code
...
}
The main reason for this doesn't really jump out with a simple example as above - it's more crucial in multi-line statements like
foo
.bar // scalastyle:ignore
.baz
Does anyone know a way to do this?

C/C++ Is it possible to #undef a serial of macro starting by the same patern?

I'm writing a tool using macros to generate enum. When done, I want to undef all those macros, but I don't know all names yet. Somes will comes later in developement. So I want to make a generic undef like...
#undef ENUM_*
Is that possible ? The macros simplified looks like that:
First...
#define ENUM_VALUE(VALUE) VALUE,
#define ENUM_STRING(STRING) #STRING,
#define ENUM_GENERATE(NAME)\
namespace NAME {\
enum Enum: int { ENUM_##NAME(ENUM_VALUE) };\
const char *Names[] = { ENUM_##NAME(ENUM_STRING) };\
}\
Then for each enum I define...
#define ENUM_MyEnum(VALUE)\
VALUE(Value1)\
VALUE(Value2)\
VALUE(Value3)
ENUM_GENERATE(MyEnum)
It generate a synchronized enum and string table like if I had declared
namespace MyEnum {
enum Enum: int { Value1, Value2, Value3 };
const char *Names[] = { "Value1", "Value2", "Value3" };
}
The only problem is that I end with truck load of macros. Somes I don't know yet, because they will be define later when I new enums will be creted. But all start by ENUM_
Is there a simple way to undef them all ? Thanks
Here is a detailed proposal for the "base macro" idea from comment:
It leaves some defined macros behind, but guarantees that any use is blocked by a single macro not being defined.
I.e. you undef that single one and all attempts to use one of the macros from the group it represents result in a "undefined" error,
or maybe in some defined expansion, which is however sure to annoy the compiler.
// Infrastructure
#define BASE_BASE(ParWhich) BASED_##ParWhich
// Secondary infrastructure, needed for supporting parameterised macros.
#define BASE_NOPAR(ParWhich) BASE_BASE(ParWhich)
#define BASE_ONEPAR(ParWhich, ParOne) BASE_BASE(ParWhich)(ParOne)
// Potentially many macros being defined in a slightly "get-used-to" manner.
#define BASED_A Hello
#define BASED_B(ParWhat) ParWhat
#define BASED_C(ParWord) ParWord
// Example line, to be expanded by prepro with defined macro BASE_BASE.
BASE_NOPAR(A) BASE_ONEPAR(B,PreProcessor) BASE_NOPAR(B)(World.)
// The one line which should lead to compiler errors for any use of one of the macros.
#undef BASE_BASE
// Same example again.
BASE_NOPAR(A) BASE_ONEPAR(B,PreProcessor) BASE_NOPAR(B)(World.)
// Not necessary, just to make sure and to make readable prepro-output.
#define BASE_BASE(ParIgnore) Compiler, please fail here!
// Same example again.
BASE_NOPAR(A) BASE_ONEPAR(B,PreProcessor) BASE_NOPAR(B)(World.)
Using the parameter-free base macro with a parameter in a following pair braces, as done in the example BASE_NOPAR(C)(World.)
should not be done directly in code anywhere; because it would, in my opinion,
turn into maintenance nightmare soon.
I.e. it should be done in a central "core" place as demonstrated otherwise.
Wouldn't want any code written like that.
Output:
>gcc -E -P BaseMacro.c
Hello PreProcessor World.
BASE_BASE(A) BASE_BASE(B)(PreProcessor) BASE_BASE(B)(World.)
Compiler, please fail here! Compiler, please fail here!(PreProcessor) Compiler, please fail here!(World.) Compiler, please fail here!(World.)

Never before seen syntax in Objective-C: open/close braces w/out method/conditional statement, what is the purpose?

I am looking over an Xcode project I downloaded and am seeing code syntax that I am unfamiliar with:
The braces don't belong to a method signature, or any other conditional statement, they are just floating there. What is the point of this? Purely for code segregation/readability purposes?
This is just block scope; and is the same in C and C++. Any variables declared within the block are inaccessible outside of it. I commonly use it in switch statements:
switch(x) {
case 1: {
const char *s = "hi";
}
break;
case 2: {
const char *s = "ho";
}
break;
// etc.
}
Note that there are two variables called s, neither of which interfere with the other as they are within their own scope.
The declarations within the scope enclosed by the braces will be confined to that scope, so label, icon, and button will not be visible outside of it. As such it provides locality which is generally considered to be good.
Legacy code needed { } in order to do declarations at all
In C89, you couldn't just do int i; anywhere; declarations were only valid at the beginning of blocks.
check this for more explanation
Why enclose blocks of C code in curly braces?

; expected but <place your favourite keyword here> found

I'm trying to write a class for a scala project and I get this error in multiple places with keywords such as class, def, while.
It happens in places like this:
var continue = true
while (continue) {
[..]
}
And I'm sure the error is not there since when I isolate that code in another class it doesn't give me any error.
Could you please give me a rule of thumb for such errors? Where should I find them? are there some common syntactic errors elsewhere when this happens?
It sounds like you're using reserved keywords as variable names. "Continue", for instance, is a Java keyword.
You probably don't have parentheses or braces matched somewhere, and the compiler can't tell until it hits a structure that looks like the one you showed.
The other possibility is that Scala sometimes has trouble distinguishing between the end of a statement with a new one on the next line, and a multi-line statement. In that case, just drop the ; at the end of the first line and see if the compiler's happy. (This doesn't seem like it fits your case, as Scala should be able to tell that nothing should come after true, and that you're done assigning a variable.)
Can you let us know what this code is inside? Scala expects "expressions" i.e. things that resolve to a particular value/type. In the case of "var continue = true", this does not evaluate to a value, so it cannot be at the end of an expression (i.e. inside an if-expression or match-expression or function block).
i.e.
def foo() = {
var continue = true
while (continue) {
[..]
}
}
This is a problem, as the function block is an expression and needs to have an (ignored?) return value, i.e.
def foo() = {
var continue = true
while (continue) {
[..]
}
()
}
() => a value representing the "Unit" type.
I get this error when I forget to put an = sign after a function definition:
def function(val: String):Boolean {
// Some stuff
}

How to redefine a macro using its previous definition

Suppose I have the following macro:
#define xxx(x) printf("%s\n",x);
Now in certain files I want to use an "enhanced" version of this macro without changing its name. The new version explores the functionality of the original version and does some more work.
#define xxx(x) do { xxx(x); yyy(x); } while(0)
This of course gives me redefition warning but why I get 'xxx' was not declared in this scope? How should I define it properly?
EDIT: according to this http://gcc.gnu.org/onlinedocs/gcc-3.3.6/cpp/Self_002dReferential-Macros.html it should be possible
Not possible. Macros can use other macros but they are using the definition available at expand time, not definition time. And macros in C and C++ can't be recursive, so the xxx in your new macro isn't expanded and is considered as a function.
Self-referential macros do not work at all:
http://gcc.gnu.org/onlinedocs/cpp/Self_002dReferential-Macros.html#Self_002dReferential-Macros
If you're working on C++ you can obtain the same results with template functions and namespaces:
template <typename T> void xxx( x ) {
printf( "%s\n", x );
}
namespace my_namespace {
template <typename T> void xxx( T x ) {
::xxx(x);
::yyy(x);
}
}
You won't be able to reuse the old definition of the macro, but you can undefine it and make the new definition. Hopefully it isn't too complicated to copy and paste.
#ifdef xxx
#undef xxx
#endif
#define xxx(x) printf("%s\n",x);
My recommendation is defining an xxx2 macro.
#define xxx2(x) do { xxx(x); yyy(x); } while(0);
If we know type of 'x' parameter in the 'xxx' macro, we can redefine macro by using it in a function and then define the 'xxx' macro as this function
Original definition for the 'xxx' macro:
#define xxx(x) printf("xxx %s\n",x);
In a certain file make enhanced version of the 'xxx' macro:
/* before redefining the "xxx" macro use it in function
* that will have enhanced version for "xxx"
*/
static inline void __body_xxx(const char *x)
{
xxx(x);
printf("enhanced version\n");
}
#undef xxx
#define xxx(x) __body_xxx(x)
From: https://gcc.gnu.org/onlinedocs/gcc/Push_002fPop-Macro-Pragmas.html
#define X 1
#pragma push_macro("X")
#undef X
#define X -1
#pragma pop_macro("X")
int x [X];
It is not exactly what you're asking for but it can help.
You can #undef a macro prior to giving it a new definition.
Example:
#ifdef xxx
#undef xxx
#endif
#define xxx(x) whatever
I never heard of (or seen) a recursive macro though. I don't think it is possible.
This answer doesn't answer your question exactly, but I feel like it does a good job at working the way you would intend to use your method (if it was possible).
The idea is for all of your file-specific macros that do actual work to have a unique name (for example LOG_GENERIC and LOG_SPECIFIC), and having the common token (in your case xxx) simply point to the currently appropriate macro.
Plus, using non-standard but widely available #pragma push_macro and #pragma pop_macro we can both modify the common xxx token and restore it to the previous version.
For example, imagine two header files, generic.hpp and specific.hpp, common token here being LOG:
// generic.hpp
#pragma once
#include <cstdio>
#define LOG_GENERIC(x) printf("INFO: " x "\n")
#define LOG LOG_GENERIC
void generic_fn(){LOG("generic");} // prints "INFO: generic\n"
// specific.hpp
#pragma once
#include "generic.hpp"
#define LOG_SPECIFIC(x) do {printf("<SPECIFIC> "); LOG_GENERIC(x);} while (0)
#pragma push_macro("LOG")
#undef LOG
#define LOG LOG_SPECIFIC
void specific_fn(){LOG("specific");} // prints "<SPECIFIC> INFO: specific\n"
#undef LOG
#pragma pop_macro("LOG")
By doing things this way we get the benefits of:
an easy mechanism to modify LOG in a restorable way via #pragma push_macro and #pragma pop_macro
being able to refer to certain LOG_* macros explicitly (LOG_SPECIFIC can use LOG_GENERIC)
we can't refer to LOG inside of LOG_SPECIFIC definition, we have to go through LOG_GENERIC
this is different to your question, but personally I am of the opinion that this is the better design, otherwise you gain the ability to allow macros above the LOG_SPECIFIC definition to affect it, just sounds like the wrong thing to do every time
Link to a github repository with the example above