문제

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. 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. 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?

or, in other words:

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

It would also be interesting to know if this behaviour is supported by other compilers (or at least 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.

Thanks to Maurits and Neil! I didn't think about using -pedantic to check!

도움이 되었습니까?

해결책

In GNU C language extensions casting to a union is marked as an extension to the C standard. So most probably you won't find it in the C99 or any other C standard. The IBM C compiler supports this extension as well.

다른 팁

이 문제를 다시 만들 수있었습니다.수정 사항은 큰 따옴표 사이의 수식에 빈 공간을 갖는 것입니다. 수식은 다음과 같아야합니다.

IF(Availability="Out of stock"," ",Item)
.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top