Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++: How to use the do-while(0); construct without compiler warnings like C4127?

I'm often use do-while(0) construct in my #defines, for the reasons described in this answer. Also I'm trying to use as high as possible warning level from compiler to catch more potential problem and make my code more robust and cross-platform. So I'm typically using -Wall with gcc and /Wall with MSVC.

Unfortunately MSVC complain about do-while(0) construct:

foo.c(36) : warning C4127: conditional expression is constant 

What should I do about this warning?

Just disable it globally for all files? It does not seems to be good idea for me.

like image 256
bialix Avatar asked Dec 22 '09 13:12

bialix


People also ask

Do compiler warnings matter?

They are not errors from the viewpoint of a programming language, but they may be software bugs. However, many compilers can be customized so that their warnings don't stop the compilation process. Warnings must not be ignored. You'd better fix every possible error before starting software testing.

How do you ignore warnings in C++?

To disable a set of warnings for a given piece of code, you have to start with a “push” pre-processor instruction, then with a disabling instruction for each of the warning you want to suppress, and finish with a “pop” pre-processor instruction.

Will warnings affect whether your code compiles C++?

Compilers emit both erorrs, which prevent your code from compiling at all, and warnings, which indicate a potential problem, but still let your code compile. (Unless you have ask the compiler to treat warnings as errors, such as with the -Werror flag to gcc).


2 Answers

Summary: This warning (C4127) in this particular case is a subtle compiler bug. Feel free to disable it.

In depth:

It was meant to catch situations when logical expression evaluates to a constant in non-obvious situations (such as, if(a==a && a!=a), and somehow, it turned while(true) and other useful constructs into invalid.

Microsoft recommends using for(;;) for infinite loop if you want to have this warning on, and there is no solution for your case. This is one of very few Level-4 warnings my company's development conventions allow to disable.

like image 157
Pavel Radzivilovsky Avatar answered Oct 03 '22 00:10

Pavel Radzivilovsky


Perhaps your code needs more owls:

do { stuff(); } while (0,0) 

Or the less photogenic but also less warning producing:

do { stuff(); } while ((void)0,0) 
like image 28
Eric Seppanen Avatar answered Oct 03 '22 00:10

Eric Seppanen