I ran into this today in an if and after looking into it found that all these are all valid statements that generate the C4353 . My only guess is that this is the old way of doing noop in C. Why is this not an error. When would you use this to do anything useful.
int main()
{
nullptr();
0();
(1 == 2)();
return 0;
}
Using constant 0 as a function expression is an extension that is specific to Microsoft. They implemented this specifically because they saw a reason for it, which explains why it's wouldn't make sense to treat it as an error. But since it's non-standard, the compiler emits a warning.
You are correct that it is an alternative to using __noop().
All of these :
nullptr();
0();
(1 == 2)();
are no-op statements (meaning they don't do anything).
btw I hope you are not ignoring warnings. Most of the time it is a good practice to fix all warnings.
As explained in the C4353 warning page and in the __noop intrinsic documentation, the use of 0 as a function expression instructs the Microsoft C++ compiler to ignore calls to the function but still generate code that evaluates its arguments (for side effects).
The example given is a trace macro that gets #defined either to __noop or to a print function, depending on the value of the DEBUG preprocessor symbol:
#if DEBUG
#define PRINT printf_s
#else
#define PRINT __noop
#endif
int main() {
PRINT("\nhello\n");
}
The MSDN page for that warning has ample explanation and a motivating example:
// C4353.cpp
// compile with: /W1
void MyPrintf(void){};
#define X 0
#if X
#define DBPRINT MyPrint
#else
#define DBPRINT 0 // C4353 expected
#endif
int main(){
DBPRINT();
}
As you can see it is to support archaic macro usage.
Related
I am trying to understand some C++ code and this piece of code is confusing me.
#ifndef NDEBUG
#define ukd_assert(expr) \
((void)((expr) ? 0 : (Assert::failedAssert(), 0)))
#else // NDEBUG
#define INSTANTIATE_ASSERT(fp)
#define ukd_assert(expr) ((void)0)
#endif // NDEBUG
Can anyone tell me how to interpret this?
As from the comments to the question:
I am not sure what ((void)((expr) ? 0 : (Assert::failedAssert(), 0))) does. I know it calls the function failedAssert but not much else.
The fact is that the ternary operator requires that both operands are of the same type (you can freely ignore the few exceptions to this rule for your case).
Even though you didn't provide a declaration for Assert::failedAssert(), I strongly suspect that its return type is void. The comma operator makes possible to have int as the type of the expression:
(Assert::failedAssert(), 0)
Therefore the types of the two expressions of the ternary operator are int and the code happily compiles.
The first (void) just serves the purpose of suppressing a warning instead.
I've been inspecting someone's code and I encountered this:
#else //If not in Debug mode
#define LOG_WARNING(str) do { (void)sizeof(str); } while(0)
#define LOG_INFO(str) do { (void)sizeof(str); } while(0)
// ... More #define directives
#endif
Apparently, do { (void)sizeof(str); } while(0) is carefully written so the directive can be completely ignored by the compiler.
How does this work?
The operand of sizeof is an unevaluated, so this ensures that there is no work to be done at run time. The macro just ignores a constant value; the compiler can see that it has no effect, so should generate no code from it.
The advantage over doing nothing at all is that the compiler still checks that the argument is a valid expression; you won't accidentally break the debug build when changing the code and only compiling for release.
The advantage over (void)str, mentioned in the comments, is that that would evaluate the expression, and the compiler might not be able to eliminate it, since it there might be side effects. For example:
extern std::string get_message(int code);
LOG_INFO(get_message(code)); // -> (void)get_message(code);
in a release build would call the function and ignore the result, impacting performance.
Is there a generic suppress warning that i can use?
The problem is that there are times i may build using one compiler version (gcc) and then i have a partner that uses some of the common things but uses a different compiler. So the warning # are different.
The only way i could think of doing was making a macro that was defined in a file that i would pass in some generic value:
SUPPRESS_WARNING_BEGIN(NEVER_USED)
//code
SUPPRESS_WARNING_END
then the file would have something like:
#if COMPILER_A
NEVER_USED = 245
#endif
#if COMPILER_B
NEVER_USED = 332
#endif
#define SUPPRESS_WARNING_BEGIN(x) /
#if COMPILER_A
//Compiler A suppress warning x
#endif
#if COMPILER_B
//Compiler B suppress warning x
#endif
#define SUPPRESS_WARNING_END /
#if COMPILER_A
// END Compiler A suppress warning
#endif
#if COMPILER_B
// END Compiler A suppress warning
#endif
Don't know if there is an easier way? Also i know ideally we all would just use the same compiler but that is unfortunately not an option. Just trying to find the least complicated way to support something like this and am hoping there is a simpler way then mentioned above.
thanks
There's no portable way to do that. Different compilers do it in different ways (e.g. #pragma warning, #pragma GCC diagnostic, etc.).
The easiest and best thing to do is to write code that does not generate any warnings with at compiler at any warning level.
If your goal is to suppress warnings about unused variables, I recommend using a macro:
#define UNUSED(x) ((void)sizeof(x))
...
void some_function(int x, int y)
{
// No warnings will be generated if x is otherwise unused
UNUSED(x);
....
}
The sizeof operator is evaluated at compile-time, and the cast to void produces no result, so any compiler will optimize the UNUSED statement away into nothing but consider the operand to be used.
GCC also has the unused attribute`:
// No warnings will be generated if x is otherwise unused
int x __attribute__((unused));
This isn't a typical question to solve a specific problem, it's rather a brain exercise, but I wonder if anyone has a solution.
In development we often need to disable or switch some parts of code to check different approaches. To do this we use comments or #defines, but my favorite is:
//*
[code here]
//*/
Now when you remove just the first slash the code will become commented-out.
The question: is there any way to implement similar if-else code switch? I tried to find it but I always had some problem and couldn't find a working solution.
And maybe do you know any similar tricks?
Wrapping the code with #if 0 does the trick but then you still need to edit the code to enable/disable it. That's not much better than just using the comment block.
Note that you can also use a defined preprocessor constant:
#ifdef ENABLE_TESTS
// code that you want to run ONLY during tests
#endif
Now when building the code, you can selectively define/un-define this constant in your build process - IDE/makefile/build script/command-line - without needing to edit the code:
$ gcc -DENABLE_TESTS source.c
I've added this answer to counter-balance all of the early #if 0 answers, but this construct from the accepted answer is the best answer to the specific question: /**/ foo(); /*/ bar(); /**/. Please use such comment tricks sparingly.
#if 0
...disabled code here
#endif
I'm not sure I should post this because it's not something I think is 'good code', but I'll admit to having used the following technique as a quick-n-dirty way to be able to quickly switch between two small snippets of code when I'm just checking something out:
// in the following , foo() is active:
/**/ foo(); /*/ bar(); /**/
Now just remove one of the asterisks at the front:
// now bar() is active:
/*/ foo(); /*/ bar(); /**/
Of course, this should never make it past the "just checking things out" phase...
Preprocessor if-else also works
#if 1
// ... enabled if 1
#else
// ... enabled if 0
#endif
Use some preprocessor logic to help you out here:
#if 0
//code goes here
#endif
Enjoy
Sometimes I use the below trick to switch between two lazy comments.
//* <-- remove the first slash
[code block 1]
/*/
[code block 2]
//*/
Well, if the code that needed to be disabled once or twice before finalizing, I prefer to use hotkeys provided by IDE to comment that code out, and later comment in. Yes, I need to select the code block first, but I prefer not to include one more debugging variable/preprocessor directive/if statement every time I need to disable a part of code. This happens to be most of the time.
If, on the other hand, I need to repeatedly switch between 2 code blocks to find the right thing, then I use a if (0) / if (1) to disable/enable code block.
[code block 1]
Later
if (0)
{
[code block 1]
}
else
{
[code block 2]
}
If you're doing checks at compile time, you can use Gigi's answer, which will conditionally not compile sections of code. Note that the preprocessor has no knowledge of variables, or sizeof, or other things handled by the compiler (so using something like 4 == sizeof(int) will not fly)
If you want to compile in little bits of debugging code that should not ever get run, you can use regular conditional statements, like such
bool debugging = false;
// banana banana banana
if (debugging)
{
// do a bunch of stuff here
}
You can then use a debugger to access the skipped section by assigning debugging to true.
Macro is the way to do this..
#define COMPILE
#ifdef COMPILE
//code to comment begins
cout<<"ha ha ha"<<endl;
//code to comment ends
#endif
To disable the code, just comment out #define compile line
Synchronously switching on/off chunks of code scattered across the program is sometimes a need too.
Inspired by this earlier post by Graham I cooked up something like this:
void doNothing(){}
#define DO_IF(flag, code) flag ? code : doNothing();
This can be for instance used as follows:
DO_IF(collectStats, recordStats());
DO_IF(collectStats, store(pullStat()));
An that is even better:
#define DO_IF(flag,code) if( flag ) { code; }
1 ? foo() : bar();
This executes foo(). Change the 1 to a 0 to execute bar() instead.
Unlike the suggestions involving preprocessor directives or comments, both possible branches are compiled, so you get the full benefit of the compiler's syntax checking.
Sometimes i use this approach to just not overbloat the code by infinite sequence of if-endif definitions.
debug.hpp
#ifdef _DEBUG
#define IF_DEBUG(x) if(x)
#else
#define IF_DEBUG(x) if(false)
#endif
example.cpp
#include "debug.hpp"
int a,b, ... ,z;
...
IF_DEBUG(... regular_expression_here_with_a_b_z ...) {
// set of asserts
assert(... a ...);
assert(... b ...);
...
assert(... z ...);
}
This is not always effective, because compiler may warn you about unused variables has used inside such disabled blocks of code. But at least it is better readable and unused variable warnings can be suppressed for example like this:
IF_DEBUG(... regular_expression_here_with_a_b_z ...) {
// set of asserts
assert(... a ...);
assert(... b ...);
...
assert(... z ...);
}
else {
(void)a;
(void)b;
....
(void)z;
}
It is not always a good idea, but at least helps to reorganize the code.
the following logic should contain the simplest approach
if(isMode1)
{
//Code for mode1
}
else
{
//Code for other modes
}
although I think the correct way is to use PreProcessor Directives
In my code, I like to do this in my main.cpp file:
#define CRAZY_EXPERIMENT
#ifdef TEST
#include "Test.h"
#elif ANOTHER_TEST
#include "AnotherTest.h"
#elif CRAZY_EXPERIMENT
#include "CrazyExperiment.h"
#else
int main(int argc, int * argv[]){
runTheProgramLikeNormal();
}
#endif
The header files you see all contain their own main(). There is only ever one main() function in the program based on what is defined in the first #define there. If the statement is omitted entirely, it defaults to the canonical main() function you see written.
This makes it easy to write tests for my program that only focus on one or two components by themselves. And the best part is that the test headers are neatly quarantined from my code, so no test code gets left in (or even linked in) by mistake.
Is it possible to do something like this
#ifdef SOMETHING
#define foo //
#else
#define foo MyFunction
#endif
The idea is that if SOMETHING is defined, then calls to foo(...) become comments (or something that doesn't get evaluated or compiled), otherwise it becomes a call to MyFunction.
I've seen __noop used, but I don't believe I can use that.
EDIT(s):
I don't think I can really use a macro here, because MyFunction takes a variable number of arguments.
Also, I'd like to make it so the arguments are NOT evaluated! (So doing something like commenting out the body of MyFunction doesn't really give me what I need, as the arguments will still be evaluated)
Try this:
#ifdef SOMETHING
#define foo(x)
#else
#define foo(x) MyFunction(x)
#endif
If your function has several arguments, then:
#ifdef SOMETHING
#define foo(x,y,z)
#else
#define foo(x,y,z) MyFunction(x,y,z)
#endif
If your function has a variable number of arguments, then your compiler may support so-called "variadic macros", like this:
#ifdef SOMETHING
#define foo(...)
#else
#define foo(...) MyFunction(__VA_ARGS__)
#endif
The reason which I've seen this kind of thing used in practice is to get rid of logging functions from a release build. However, see also Separate 'debug' and 'release' builds? in which people question whether you should even have different builds.
Alternatively, instead of redefining the function call as nothing, Jonathan's comment to this answer suggested doing something like the following:
#ifdef SOMETHING
#define foo(...) do { if (false) MyFunction(__VA_ARGS__) } while (0)
#else
#define foo(...) do { if (true) MyFunction(__VA_ARGS__) } while (0)
#endif
The reasoning for doing this is so that the function call is always compiled (so it won't be left with gratuitous errors like references to deleted variables), but only called when needed: see Kernighan & Pike The Practice of Programming and also the Goddard Space Flight Center programming standards.
From a debug.h file (originating from 1990, and therefore not using __VA_ARGS__):
/*
** Usage: TRACE((level, fmt, ...))
** "level" is the debugging level which must be operational for the output
** to appear. "fmt" is a printf format string. "..." is whatever extra
** arguments fmt requires (possibly nothing).
** The non-debug macro means that the code is validated but never called.
** -- See chapter 8 of 'The Practice of Programming', by Kernighan and Pike.
*/
#ifdef DEBUG
#define TRACE(x) db_print x
#else
#define TRACE(x) do { if (0) db_print x; } while (0)
#endif /* DEBUG */
With C99, there's no longer a need for the double parentheses trick. New code should not use it unless C89 compatibility is an issue.
Maybe an easier way to do this would be to conditionally omit the body of the function?
void MyFunction() {
#ifndef SOMETHING
<body of function>
#endif
}
Unless you specifically don't want a function call to be made at all, this seems like a clean way to achieve your goal.
Unfortunately the current C++ version doesn't support variadic macros.
However, you can do this:
#ifdef SOMETHING
#define foo
#else
#define foo(args) MyFunction args
#endif
// you call it with double parens:
foo((a, b, c));
If, in the case you don't want foo called, you define it as:
void foo() {}
any calls to foo() should be optimized way.
What about something along these lines:
#ifdef NDEBUG
#define DEBUG(STATEMENT) ((void)0)
#else
#define DEBUG(STATEMENT) (STATEMENT)
#endif
You would use it like this to log debugging messages:
DEBUG(puts("compile with -DNDEBUG and I'm gone"));
A non-generic version for formatted output with additional debugging information using C99 variadic macros and the __func__ identifier could look like this:
#ifdef NDEBUG
#define Dprintf(FORMAT, ...) ((void)0)
#define Dputs(MSG) ((void)0)
#else
#define Dprintf(FORMAT, ...) \
fprintf(stderr, "%s() in %s, line %i: " FORMAT "\n", \
__func__, __FILE__, __LINE__, __VA_ARGS__)
#define Dputs(MSG) Dprintf("%s", MSG)
#endif
Here's how you'd use these macros:
Dprintf("count = %i", count);
Dputs("checkpoint passed");
Likely, you don't want to do the simple "code removal" as suggested,
because your callers will be expecting the side effects of the
arguments to happen. Here are some troublesome caller snippets that
should get you thinking:
// pre/post increment inside method call:
MyFunction(i++);
// Function call (with side effects) used as method argument:
MyFunction( StoreNewUsernameIntoDatabase(username) );
If you were to disable MyFunction by simply saying:
#define MyFunction(x)
then the side effects that the callers were expecting would go away,
and their code would break, and be quite difficult to debug. I like
the "sizeof" suggestion above, and I also like the suggestion to just
disable the body of MyFunction() via #ifdef's, although that means
that all callers get the same version of MyFunction(). From your
problem statement, I presume that's not actually what you want.
If you really need to disable MyFunction() via preprocessor defines on
a per-source-file basis, then I'd do it like this:
#ifdef SOMETHING
#define MyFunction(x) NoOp_MyFunction(x)
int NoOp_MyFunction(x) { }
#endif
You could even include the implementation of NoOp_MyFunction() inside
the source & headers for MyFunction(). You also have the flexibility
to add extra logging or debugging information in NoOp_MyFunction() as
well.
No, the C and C++ Standards say you cannot #define something to be a comment, so
#define foo //
won't work.
#ifdef SOMETHING
#define foo sizeof
#else
#define foo MyFunction
#endif
I'm assuming that foo is a printf style function? Anyways, this won't work with a zero parameter function, but if that were the case, you would already know what to do. If you really want to be anal you can use (void)sizeof but that's probably unnecessary.
I'm a little reluctant to post this answer because it's use of macro hackery can become the source of problems. However - if the calls to the function you want to have disappear are always used alone in a statement (ie., they are never part of a larger expression), then something like the following could work (and it handles varargs):
#ifdef SOMETHING
#define foo (1) ? ((void) 0) : (void)
#else
#define foo MyFunction
#endif
So if you have the line of code:
foo( "this is a %s - a++ is %d\n", "test", a++);
it will end up after the preprocessing step as either:
MyFunction( "this is a %s - a++ is %d\n", "test", a++);
or
(1) ? ((void) 0) : (void)( "this is a %s - a++ is %d\n", "test", a++);
which turns the pseudo-function's parameter list into a bunch of expressions separated by the comma operator that will never be evaluated, since the conditional always returns the ((void) 0) result.
A variant of this is something close to what ChriSW and Jonathan Leffler suggested:
#ifdef SOMETHING
#define foo if (0) MyFunction
#else
#define foo if (1) MyFunction
#endif
This is slightly different in that it does not require the compiler to support variadic macros (__VA_ARGS__).
I think this can be useful for eliminating debug trace function calls which are generally never combined into a larger expression, but beyond that I think it's a dangerous technique.
Note the potential for problems - especially if the parameters in the call produce side-effects (this is a general problem with macros - not just this hack). In the example, the a++ will be evaluated only if SOMETHING is defined in the build, otherwise it's not. So if code after the call depends on the value of a to be incremented, one of the builds has a bug.
If I remember correctly, you should be able to #define your macro to "nothing" and that will cause the compiler to ignore that call
#define foo()
foo(); // this will be ignored
What about surrounding each call to myFunction with
#ifdef SOMETHING
myFunction(...);
#endif
?