Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is parameter not a constant expression?

Tags:

c++

gcc

c++14

Could you please explain why this code doesn't compile?

// source.cpp
constexpr const char* func(const char* s) { return s;}

constexpr bool find(const char *param) {
   constexpr const char* result = func(param);
   return (param == 0);
}

int main()
{
   constexpr bool result = find("abcde");
}

The compile command:

$ g++ -std=c++14 source.cpp

I've tried gcc5.4 and gcc6.4. The error:

source.cpp: In function ‘constexpr bool find(const char*)’:
source.cpp:5:46: error: ‘param’ is not a constant expression
 constexpr const char* result = func(param);
                                          ^
like image 462
embedc Avatar asked Jan 29 '19 12:01

embedc


People also ask

Is it possible to use a constant in a parameter?

A constant parameter is declared in the case when it is necessary that the value of the transferred object remains unchanged in the body of the called function. This case is possible when the argument's value is passed by the address when function is called.

What is meant by constant expression?

A constant expression is an expression that can be evaluated at compile time. Constants of integral or enumerated type are required in several different situations, such as array bounds, enumerator values, and case labels. Null pointer constants are a special case of integral constants.

What is const parameter?

A constant parameter, declared by the keyword const , is a read-only parameter. This means that we can not modify the value of the constant parameter in the function body. Using the const keyword tells the compiler that the value of that parameter will not be changed inside the function.

What is const expression in c++?

A constant value is one that doesn't change. C++ provides two keywords to enable you to express the intent that an object is not intended to be modified, and to enforce that intent. C++ requires constant expressions — expressions that evaluate to a constant — for declarations of: Array bounds.


1 Answers

A function parameter is never a constant expression. Remember that constexpr functions are just like regular functions. They can be called at run-time too. So we cannot assume the address passed in param is to something that is a constant expression, and so cannot use it to initialize a constexpr variable or return value.

You can pass string literals to constexpr functions and produce constexpr results, for instance:

constexpr bool find(const char *param) {
   return (param[0] == 0);
}

int main()
{
   constexpr bool result = find("abcde"); // OK!
}

The function is callable in a constant expression, when given a constant expression. But it cannot assume it is only ever called in a constant expression (I know, one can go cross-eyed thinking about it).

like image 91
StoryTeller - Unslander Monica Avatar answered Oct 06 '22 20:10

StoryTeller - Unslander Monica