C++14 constexpr relaxations


C++14 has allowed certain operations in the constexpr functions.Meaning it has become less strict on the rules imposed upon the constexpr functions.Here are some of the relaxations made by C++14.

Variable declaration is allowed inside constexpr

Variable declaration is allowed inside constexpr function,but the variable must be initialized and it cannot be static type.

Code example

constexpr int func( )
{
int val=90; //work fine

int i; //error,not initialized
static int si=89; //error,static type

return val ;
}


 


Stop wasting time,earn money($$$) from your website-Join Now!

Conditional statements are allowed inside constexpr function

C++14 allows conditional statements like if( ) ,switch( ) statements are allowed inside constexpr function.

Code example

constexpr int func( int arg)
{
///Work fine
if( arg==0 )
{
 return arg;
}
else
 return 1;

return arg;
}

constexpr int funcNewer(int arg)
{
//Work fine
switch(arg)
{
case 0:
  arg*=arg;
  break;

case 1:
 arg+=arg;
 break;

default:
 break;
}

return arg;
}


Allows looping statements inside constexpr function

C++14 also allows using looping statement like for or while inside the constexpr function.

code example

constexpr int funcNew(int arg)
{
 for(auto i=0; i<2 ;i++ ) //work fine
 {
 arg+=arg ;
 }

while( true ) //work fine
{
 arg+=arg ;
 break;
}

return arg;
}

Link: C++11 auto keyword