This question is not bound to any specific compiler warning, the following is just an example.
Currently when I want a loop that checks an exit condition inside:
There are many cases in which satisfactory code behaves as intended yet generates a slew of warnings. This is why they're warnings rather than errors. The fact that they annoy you is good: warnings are intended to modify your behaviour. You are supposed to mend your ways, not sweep them under the carpet.
The example loop from the question could be written like this:
for (; testExitCondition();)
doSomething();
In more sophisticated cases the loop counter can be used as the state of a state machine (each action is required to update state):
for (int state = stateBegin; state == stateTerminate;)
{
switch (state)
{
case stateBegin:
//elaborate setup
break;
case state_1:
doSomething_1();
break;
case state_2:
doSomething_2();
break;
case state_n:
doSomething_n();
break;
}
My favourite way to avoid pointless C++ warnings is to use C# :)
Admittedly this produces a slew of pointless C# warnings but nothing's perfect.
Gosh, look at the negative votes. Proof that C++ damages your sense of humour.
I'd write for(;;)
because that's idiomatic.
Newer versions of Visual C++ are not as idiot as earlier versions were wrt. warnings. Visual C++ 10.0 compiles code that uses <windows.h>
, at warning level 4, no warnings.
But if you want to turn off Visual C++ sillywarnings, take a look at my old anti-sillywarnings header, which was created with input from the [comp.lang.c++] community.
I'd go with for(;;)
even without that warning. It's not stupid: it's a loop with no condition, which is exactly what you want to express.
That seems more logical to me than using a while loop and testing that true is still true each time round the loop (of course the compiler will optimize away this test, so it won't actually affect performance).
I use while(true, 1) to suppress this warning.
My philosophy is that if you make the compiler suppress warnings, put a comment in there and tell why. Even if you think it's silly. Pragma stands out and is visible. It's a fine comment in your code.
When you start skipping comments when suppressing warnings based on your idea on how silly it is, you are heading for potential trouble. Another person working on your code after a year might change it, have trouble and waste precious time hunting it down.
Btw, you are looking for a way of suppressing the warnings without either
That would be a very hidden suppression method.
If you don't like the look of pragma, use
bool alwaysTrue = true; // to prevent compiler warning C4127
while (alwaysTrue) {
...
}
Do some funny token pasting: if you can swap
while(true)
for
While(true)
then just do the following:
#define while_true for( ;; )
#define While(a) while_##a