Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are function addresses not constant expressions

Is there a way to use function addresses in constant expressions?

void foo()
{}

int main()
{
  static_assert(&foo, "test error");
}

This won't compile.

error C2057: expected constant expression

The intention behind this is that I want to compare two function addresses at compile time.

like image 316
cooky451 Avatar asked Mar 04 '12 16:03

cooky451


2 Answers

It is most definitely a compiler bug.

Functions can be used as template argument to template, which means they are const expressions. (See ideone).

Also, the above code compiles fine with gcc 4.6.1, though ideone doesn't compile it, but ideone uses gcc-4.5.1 which has bug with regard to your code.

like image 107
Nawaz Avatar answered Sep 24 '22 17:09

Nawaz


This is my understanding, FWIW:

A function type is known a compile time, but a function address is only known at link time. Thus, you can use function types as template parameters, yet addresses are not constant/known at compile time.

In your sample code, the compiler could deduce that the address is nonzero at compile time, but it wouldn't be able to know the specific address then. This is not a compiler bug, though.

like image 22
Nick Avatar answered Sep 22 '22 17:09

Nick