How to disable C4127 for do {} while(false)

6.3k Views Asked by At

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

//file error.h

        #define FAIL(message) \
        do { \
            std::ostringstream ossMsg; \
            ossMsg << message; \
            THROW_EXCEPTION(ossMsg.str());\
        } while (false)


//main.cpp

...

FAIL("invalid parameters"); // <<< warning C4127: conditional expression is constant    

...

As you can see the warning is related to the do {} while(false).

I can only figure out the following way to disable the warning:

        #pragma warning( push )
        #pragma warning( disable : 4127 )
        FAIL("invalid parameters");
        #pragma warning( pop )

but I don't like this solution.

I also tried to put those macro in error.h without effect.

Any comments on how to suppress this warning in a decent way?

Thank you

2

There are 2 best solutions below

6
djechlin On

1) Why not just THROW_EXCEPTION("invalid parameters")?
2) while(true) and break at the end?

7
AudioBubble On

The warning is due to the while(false). This site gives an example of how to workaround this problem. Example from site (you'll have to re-work it for your code):

#define MULTI_LINE_MACRO_BEGIN do {  
#define MULTI_LINE_MACRO_END \  
    __pragma(warning(push)) \  
    __pragma(warning(disable:4127)) \  
    } while(0) \  
    __pragma(warning(pop))

#define MULTI_LINE_MACRO \  
        MULTI_LINE_MACRO_BEGIN \  
            std::printf("Hello "); \  
            std::printf("world!\n"); \  
        MULTI_LINE_MACRO_END  

Just insert your code between the BEGIN and END:

#define FAIL(message) \  
    MULTI_LINE_MACRO_BEGIN \  
        std::ostringstream ossMsg; \
        ossMsg << message; \
        THROW_EXCEPTION(ossMsg.str());\  
    MULTI_LINE_MACRO_END