Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is constexpr if with initializer guaranteed by the standard? 'constexpr(constexpr auto x = f(); x) { }'

I can't find any information about new C++17 if initializer syntax and 'constexpr if' in:

http://open-std.org/JTC1/SC22/WG21/docs/papers/2016/p0128r1.html

Nevertheless, the syntax is supported by Clang-HEAD...

constexpr auto f() { return true; }
int main() {
    if constexpr(constexpr auto x = f(); x) { }
}

online code here -> http://melpon.org/wandbox/permlink/dj3a9ChvjhlNc8nr

Is the constexpr if with initializer guaranteed by the standard, as constexpr if is just an "if with constexpr" or it's not guaranteed and has to be explicitly added to the standard?

like image 884
Kris Avatar asked Jul 29 '16 09:07

Kris


People also ask

What is the point of constexpr?

constexpr indicates that the value, or return value, is constant and, where possible, is computed at compile time. A constexpr integral value can be used wherever a const integer is required, such as in template arguments and array declarations.

Why is constexpr better than #define?

#define directives create macro substitution, while constexpr variables are special type of variables. They literally have nothing in common beside the fact that before constexpr (or even const ) variables were available, macros were sometimes used when currently constexpr variable can be used.

Where are constexpr variables stored?

Everyone knows the memory location tables of C and C++ programs. For operating systems, executable code and all the static variables get copied from the hard drive disc into the allocated areas of text, static ect. in the RAM.


1 Answers

The Selection statements with initializer proposal mentions if constexpr, and states "the facilities of if constexpr work just as well with the extended if statement from this proposal".

The specification about if statement with initializer in N4606 [stmt.if]p3 explicitly allows use of if constexpr.

Here is what N4606 [stmt.if]p3 says:

An if statement of the form

if constexpr[opt] ( init-statement condition ) statement

is equivalent to

{
  init-statement
  if constexpr[opt] ( condition ) statement
}

and an if statement of the form

if constexpr[opt] ( init-statement condition ) statement else statement

is equivalent to

{
  init-statement
  if constexpr[opt] ( condition ) statement else statement
}

except that names declared in the init-statement are in the same declarative region as those declared in the condition.

like image 118
cpplearner Avatar answered Nov 04 '22 05:11

cpplearner