static-assert.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // RUN: %clang_cc1 -std=c11 -fsyntax-only -verify %s
  2. // RUN: %clang_cc1 -xc++ -std=c++11 -fsyntax-only -verify %s
  3. _Static_assert("foo", "string is nonzero");
  4. #ifndef __cplusplus
  5. // expected-error@-2 {{static_assert expression is not an integral constant expression}}
  6. #endif
  7. _Static_assert(1, "1 is nonzero");
  8. _Static_assert(0, "0 is nonzero"); // expected-error {{static_assert failed "0 is nonzero"}}
  9. void foo(void) {
  10. _Static_assert(1, "1 is nonzero");
  11. _Static_assert(0, "0 is nonzero"); // expected-error {{static_assert failed "0 is nonzero"}}
  12. }
  13. _Static_assert(1, invalid); // expected-error {{expected string literal for diagnostic message in static_assert}}
  14. struct A {
  15. int a;
  16. _Static_assert(1, "1 is nonzero");
  17. _Static_assert(0, "0 is nonzero"); // expected-error {{static_assert failed "0 is nonzero"}}
  18. };
  19. #ifdef __cplusplus
  20. #define ASSERT_IS_TYPE(T) __is_same(T, T)
  21. #else
  22. #define ASSERT_IS_TYPE(T) __builtin_types_compatible_p(T, T)
  23. #endif
  24. #define UNION(T1, T2) union { \
  25. __typeof__(T1) one; \
  26. __typeof__(T2) two; \
  27. _Static_assert(ASSERT_IS_TYPE(T1), "T1 is not a type"); \
  28. _Static_assert(ASSERT_IS_TYPE(T2), "T2 is not a type"); \
  29. _Static_assert(sizeof(T1) == sizeof(T2), "type size mismatch"); \
  30. }
  31. typedef UNION(unsigned, struct A) U1;
  32. UNION(char[2], short) u2 = { .one = { 'a', 'b' } };
  33. typedef UNION(char, short) U3; // expected-error {{static_assert failed "type size mismatch"}}
  34. typedef UNION(float, 0.5f) U4; // expected-error {{expected a type}}