将常量转换为 union

标签 c types casting

以下代码:

#include <stdio.h>

typedef union {
   int   n;
   char *s;
} val_t;

int main(void) {
  val_t v1,v2;

  v1 = (val_t)"Hello World";
  v2 = (val_t)10;

  printf("%s %d\n", v1.s, v2.n);
  return(1);
}

使用 gcc 正确编译和执行。如果尝试转换 union 中没有合适字段的常量,则会产生一条错误消息。

不过,查看 (C99) 标准时,我无法找到描述此行为的部分。因此,我的问题是:

Does the C standard guarantee that I can cast a constant to a union type, provided that the union type has a field with a compatible type?

或者,换句话说:

Is ((val_t)10) a valid rvalue of type val_t?

了解其他编译器(或至少 MS Visual C++)是否支持此行为也很有趣。有人知道吗?

编辑: 转换为 union 是 GCC 扩展,因此使用它不是一个好主意。

感谢 Maurits 和 Neil!我没有考虑使用 -pedantic 来检查!

最佳答案

GNU C language extensions强制转换为 union 被标记为对 C 标准的扩展。所以很可能您不会在 C99 或任何其他 C 标准中找到它。 IBM C 编译器也支持此扩展。

关于将常量转换为 union ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2146922/

相关文章:

c++ - 用于空 Win32 项目的智能感知

python-3.x - 为什么模拟的类型与模拟不匹配?

typescript - 通过参数使两种类型不同

c++ - `*dynamic_cast<T*>(...)` 是什么意思?

php - 取消设置数组值(将对象转换为数组后)

c - 我想将一个函数拆分成两个函数

c - 关于 C typedef struct

将 _mm_clmulepi64_si128 转换为 vmull_{high}_p64

c - 如何在带有 emxArray 参数的 C 程序中使用 MATLAB Coder codegen 创建的 C 库?

postgresql - 如何在 PostgreSQL 中创建 oid 类型的强制转换?