检查一种整数类型的值是否适合另一种类型 [英] Checking that a value of one integer type fits into another

查看:43
本文介绍了检查一种整数类型的值是否适合另一种类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两种类型 Type1Type2 由不同的标头提供,它们都是某些整数类型的 typedef,但不知道哪个(并且可能不同编译器、操作系统等).这个程序是否保证正常工作(如果它编译)

There are two types Type1 and Type2 provided by different headers, which are both typedefs for some integer types but it isn't known which (and may be different across compilers, OSes, etc. anyway). Is this program guaranteed to work correctly (if it compiles)

Type1 a = ...;
if (a == (Type2) a) {
  printf("a fits into Type2");
else {
  printf("a doesn't fit into Type2");
}

或者是否有我没有考虑的极端情况?

or are there corner cases I am not taking into account?

推荐答案

如果你只担心条目的size,使用sizeof:

If you're only worried about the size of the entry, use sizeof:

if (sizeof(a) == sizeof(Type2)) {
  printf("a fits into Type2");
else {
  printf("a doesn't fit into Type2");
}

这篇关于检查一种整数类型的值是否适合另一种类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆