简体   繁体   中英

Destinguish between types

I have the following code:

#include <iostream>
#include <string>

typedef unsigned char type1;
typedef unsigned long type2;

type1 f(type1 value)
{
    return value * 2;
}

int main()
{
  type1 value1 = 1;
  type2 value2 = 2000;
  int int1 = f(value1);
  int int2 = f(value2);  // here I would expect that the compiler warns me that I mix type1 and type2
  std::cout << int1 << std::endl;
  std::cout << int2 << std::endl;
}

Is there a way that the compiler warns me if I mix the two types type1 (unsigned char) and type2 (unsigned long)?

Thanks Teddy

Is there a way that the compiler warns me if I mix the two types type1 (unsigned char) and type2 (unsigned long)?

Yes, if you give -Wconversion to gcc or clang, or /W3 to MSVC, they will print a warning for your example.

(They will only warn you, if there is a potential value change. So, converting unsigned char to unsigned long generates no warning, as this conversion always retains value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM