2

I am working on a legacy pro* C/C++ code and migrated the project to Visual Studio 2015. When I compile the code in VS, it is giving me a below warning message at more than 100 places.

warning C4267: '=': conversion from 'size_t' to 'unsigned short', possible loss of data

and the corresponding code is

stmt.len = strlen((char*)stmt.arr); // VARCHAR stmt[500];

I was planning to change the above code to

stmt.len = static_cast<unsigned short>(strlen((char *)stmt.arr));

this will just remove the warning message. But I have to modify in more than 100 places. Is there any way to get rid of this warning message may be using some sort of macro? Please suggest.

Thanks

NJMR
  • 1,886
  • 1
  • 27
  • 46

2 Answers2

3

You can switch off the warning with

#pragma warning( disable : 4267)

although, personally, I'd work through the errors and fix correctly. Your idea with static_cast isn't a bad one, and there is no danger of undefined behaviour with overflow as you're using unsigned types.

Finally, note that using a macro to replace a standard library function is undefined behaviour. Don't do that.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • you deserve one too :) – oetoni Nov 14 '17 at 13:11
  • But I have to chagne in more than 100 places. Is there a way to replace strlen using a macro to return unsigned short.? – NJMR Nov 14 '17 at 13:11
  • @Bathsheba No! you were faster than me! that's all, you should be first – oetoni Nov 14 '17 at 13:13
  • @HJMR here a solution to that (official) https://msdn.microsoft.com/en-us/library/jj715718.aspx (other thread) https://stackoverflow.com/questions/12884331/how-to-disable-specific-warnings-for-the-entire-solution – oetoni Nov 14 '17 at 13:16
1

It's the right way to use size_t consistently. Or, there do the casting that you though as an update.

A work around for C4267 warnings and how to disable them also suggested here is:

#pragma warning (disable : 4267)

For the macro #define (only a sample)

#include <iostream>
#include <string.h>
#define strlen(x) static_cast<unsigned short>(strlen((char *)x)) 
//I tested with ((char *)x+1) and ((char *)x+2) for variation

using namespace std;

int main() {
    char stmt[] = "something";
    int len = strlen((char*)stmt); // VARCHAR stmt[500];
    cout << len;
    return 0;
}

Test here with IDEONE

oetoni
  • 3,269
  • 5
  • 20
  • 35
  • nope & thanks. I also saw that you answered much faster than me :D – oetoni Nov 14 '17 at 13:05
  • @oetoni: So I added this. #define strlen(x) static_cast(strlen((char *)x)). Please correct me if I am wrong. – NJMR Nov 14 '17 at 13:37
  • you really shouldn't do a macro with #define. as @Barthsheba said is not a defined/documented solution for your scenario but is your choice...if you choose to do so then you are right on the macro definition. That would do the trick. I am adding the code sample and test to my answer – oetoni Nov 14 '17 at 14:05