views:

430

answers:

2

The Visual Studio compiler does not seem to warn on signed/unsigned assignments, only on comparisons. For example the code below will generate a warning on the if statement but not the initial assignments.

Is there anyway to make it catch these? I'm already at W4 but thought (hoped) there may be another setting somewhere.

Thanks,

int foo(void)
{
    unsigned int fooUnsigned = 0xffffffff;
    int fooSigned = fooUnsigned; // no warning

    if (fooSigned < fooUnsigned) // warning
    {
     return 0;
    }

    return fooSigned;
}

Update:

Quamrana is right, this is controlled by warning 4365 which appears to be off by default, even at W4. However you can explicitly enable it for a given warning level like so;

#pragma warning (4 : 4365)

Which results in;

warning C4365: 'initializing' : conversion from 'unsigned int' to 'int', signed/unsigned mismatch
+4  A: 

You need to enable warning 4365 to catch the assignment.

That might be tricky - you need to enable ALL warnings - use /Wall which enables lots of warnings, so you may have some trouble seeing the warning occur, but it does.

quamrana
You could also use #pragma warning(default: 4365) to enable.
ChrisN
A: 

@quamrana:

There must be something beyond the /Wall option to enable warning 4365:

C:\Temp>cl /Wall /c foo.c
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.21022.08 for 80x86
Copyright (C) Microsoft Corporation.  All rights reserved.

foo.c
foo.c(6) : warning C4018: '<' : signed/unsigned mismatch

I see that Andrew got it to work, but does anyone have an idea why it's not working here?

The Visual Studio docs indicate that it should, but I can't even get the example program in the docs to give the C4365 warning (though it does give the related C4245 warning - but that occurs with just a /W4 option anyway).

Michael Burr