New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Py_BUILD_ASSERT is broken on non-constant expression #118124
Comments
The Python C API should be usable with older C versions. |
|
I proposed PR gh-118398 to use static_assert() in Py_BUILD_ASSERT() and Py_BUILD_ASSERT_EXPR() on C11 and newer. |
I thought that |
Use static_assert() in Py_BUILD_ASSERT() and Py_BUILD_ASSERT_EXPR() on C11 and newer and C++11 and newer. Add tests to test_cext and test_cppext.
Use static_assert() in Py_BUILD_ASSERT() and Py_BUILD_ASSERT_EXPR() on C11 and newer and C++11 and newer. Add tests to test_cext and test_cppext.
|
Fixed in the main branch. It sounds too risky to backport the change. |


Bug report
Bug description:
Macros
Py_BUILD_ASSERTandPy_BUILD_ASSERT_EXPRdefined inInclude/pymacro.hare broken whencondis not a constant expression, becausesizeofis allowed to apply on variable-length arrays(VLA) since C99 and with compiler extension since C89.Following code compiles on Clang and GCC without error:
Since CPython is now using C11 (PEP7) and
static_assertis already used in other public internal headers(e.g.Include/internal/pycore_long.h),Py_BUILD_ASSERTshould be deprecated and usestatic_assertinstead.Since they are defined in a public header of CPython without a "_Py" prefix, removing them might break third-party code.
Py_BUILD_ASSERTcan be defined tostatic_assertin a way with deprecating warning message:Py_BUILD_ASSERT_EXPRis used (and only used) in another macroPy_ARRAY_LENGTH, so it can't be deprecated yet.Fixing
Py_BUILD_ASSERT_EXPRis tricky, most because of old non-conformant MSVC1. And we need it also working in C++. The easiest fix is to change documentation so that it should be used only with constant expression or there's no assertion otherwise. But If we want to make it mandatory, here's a workaround:You can view and try the workarounds using the amazing conformance-viewer in amazing Compiler Explorer: for C and for C++.
CPython versions tested on:
CPython main branch
Operating systems tested on:
No response
Linked PRs
Footnotes
One of the unbelievable bugs is that MSVC prior to v19.21 accepts negative-length(implicitly extended to unsigned value) arrays when used as template argument, e.g.
A<char[-1]>. ↩The text was updated successfully, but these errors were encountered: