简体   繁体   English

向联盟施放常数

[英]Casting a constant to a union

The following code: 以下代码:

#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);
}

compiles and executes correctly with gcc. 使用gcc正确编译和执行。 If one tries to cast a constant for which there's not a suitable field in the union, an error message is produced. 如果试图转换一个常量,而且联合中没有合适的字段,则会产生错误消息。

Looking at the (C99) standard, though, I've not been able to locate the section where this behaviour is described. 但是,查看(C99)标准,我无法找到描述此行为的部分。 Hence, my question: 因此,我的问题:

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? 如果联合类型具有兼容类型的字段,那么C标准是否保证我可以将常量强制转换为联合类型?

or, in other words: 或者,换句话说:

Is ((val_t)10) a valid rvalue of type val_t ? ((val_t)10)是否为val_t类型的有效右值?

It would also be interesting to know if this behaviour is supported by other compilers (or at least MS Visual C++). 了解其他编译器(或至少MS Visual C ++)是否支持此行为也很有趣。 Does anybody know? 有人知道吗?

EDIT: Casting to a union is a GCC extension, so it's not a good idea to use it. 编辑:转换为联盟是一个GCC扩展,所以使用它不是一个好主意。

Thanks to Maurits and Neil! 感谢Maurits和Neil! I didn't think about using -pedantic to check! 我没想过用-pedantic检查!

In GNU C language extensions casting to a union is marked as an extension to the C standard. GNU C语言扩展中,转换为union将标记为C标准的扩展。 So most probably you won't find it in the C99 or any other C standard. 所以很可能你不会在C99或任何其他C标准中找到它。 The IBM C compiler supports this extension as well. IBM C编译器也支持此扩展。

[neilb@GONERIL NeilB]$ gcc -Wall -pedantic sw.c
sw.c: In function 'main':
sw.c:11: warning: ISO C forbids casts to union type
sw.c:12: warning: ISO C forbids casts to union type

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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