Home > Mobile >  For loop does not work (and Visual Studio gives a warning), why?
For loop does not work (and Visual Studio gives a warning), why?

Time:04-15

I isolated my code to the following test program:

#include <iostream>

using namespace std;

int main()
{
    cout << "Begin" << '\n';
    for (unsigned int c = '\200'; c < 256; c  )
    {
        cout << c << '\n';
    }
    cout << "End";

    return 0;
}

And the for loop does not run, why? I suspect it has to do with the char sizes, because it works up to '\177' and from '\200' it stops working. It seems like the character literals are treated as octal numbers, but why? And even if that is the case then '\177' is 127 and '\200' is 128 and both are still below 256?

The warning Visual Studio 2019 with the default C standard gives is:

C6294: Ill-defined for-loop: initial condition does not satisfy test. Loop body not executed.

Disclaimer: This is based on actual code and I'm trying to understand what it is doing.

CodePudding user response:

Yes, the literals are in octal, but that does not matter. You would still have the problem with hex literals, too.

The real problem is that the literals are using the char type, which is either signed or unsigned by default, the C standard leaves it up to the compiler implementation to decide which to use (some compilers have options to let the user decide). A signed char has a max value of 127, so anything higher than that will overflow to a negative value, which you are then assigning to an unsigned int, thus yielding a very large value that is > 256.

CodePudding user response:

As far as I understand it, numerical escape sequences are mapped to some char type; '\200', with octal 200 = decimal 128 is above the typical maximum char value of 127, leading it to overflow. Assigning it then to an unsigned int causes it to wrap to some large number which is above 256; at this point, the warning comes in (since a fixed value above 256 is never below 256, the loop also doesn't run).

CodePudding user response:

Firstly, you must look at the warning code.

Reference Here for C6294 warning code

Your problem is when you declare this:

unsigned int c = '\200';

c give us 4294967168 as result.

So you for loop is not correct as microsoft says in the warning code.

  •  Tags:  
  • c
  • Related