In C ++, why not “approve” a keyword?

Now "static_assert" is a keyword in C ++ 0x, I thought it would be logical to replace the macro "assert" with the keyword "assert".

+6
source share
7 answers

static_assert is interpreted at compile time, so it must be a keyword so that the compiler can process it.

assert does not have to be a keyword, and it does not make sense to make it one, because there are many ways that a program may want to respond to the success of a statement or failure. Therefore, it makes sense to implement it in a library, and it is usually implemented as a macro.

+3
source

assert does not matter compile time except during preprocessing. The preprocessor does not know the C ++ language, so the keyword does not make sense.

In contrast, static_assert is evaluated at compile time. Making it a keyword makes more sense in this regard. The compiler takes care of its existence.

There are also historical reasons; this was not a keyword in C, and make it one in C ++ to display existing assert macros as a result of undefined behavior.

+2
source

In principle, because it is not necessary. Existing approval mechanisms for runtime statements are perfectly good and do not require language support.

+2
source

Other answers give some possible answers to your question, but a recent sentence indicates that assert can indeed become a keyword in C ++ 17: https://isocpp.org/files/papers/N4154.pdf

+2
source

assert can be implemented in the library, static_assert cannot. Thus, static_assert gets the keyword because it needs language support, but assert does not.

+1
source

This cannot be done for compatibility with code already written in c that has a statement as a variable name. And therefore, as mentioned above, we will not be able to compile, since assert is no longer a macro

+1
source

In C ++ 0x (from here ):

In C ++ 0x, static statements can be declared to detect and diagnose common usage errors at compile time.

This is the static_assert syntax:

 >>-static_assert--(--constant-expression--,--string-literal-----> 

where constant-expression should be contextually converted to bool . If it converts to false , then the compiler will throw an error according to string-literal .

So this is basically an extension of the language that needs a keyword. This is not a execution mechanism.

Again from the document linked above:

Adding static statements to the C ++ language has the following advantages:

  • Libraries can detect common usage errors at compile time.

  • C ++ standard library implementations can detect and diagnose common usage errors, improving usability.

  • You can use the static_assert declaration to check for important software invariants at compile time.

+1
source

Source: https://habr.com/ru/post/889644/


All Articles