Nick
Nick

Reputation: 11384

Why can't I use an integer variable as an array key when the array is declared constexpr?

For reasons I don't understand, I can access a constexpr array's members using hard-coded integer literals as the index, but as soon as I try to use an integer variable, it fails to compile with the error undefined reference. But aIvoryKeys is in scope, and we can see this with hard-coded values.

class KeyboardKey{
   
public:
   
   static constexpr unsigned short int aIvoryKeys[] {0,2,4,5,7,9,11};
   
   void ShowIvory(){   
      
      // Hardcoded values work:
      std::cout << "aIvoryKeys " << aIvoryKeys[0] << std::endl; // 0
      std::cout << "aIvoryKeys " << aIvoryKeys[1] << std::endl; // 2
      std::cout << "aIvoryKeys " << aIvoryKeys[2] << std::endl; // 4
      
      // FAILS: undefined reference to `KeyboardKey::aIvoryKeys'
      int j = 2;
      std::cout << "aIvoryKeys " << aIvoryKeys[j] << std::endl; 
      
      // FAILS: undefined reference to `KeyboardKey::aIvoryKeys'
      for(int i=0;i<std::size(aIvoryKeys);++i){         
         std::cout << "aIvoryKeys " << aIvoryKeys[i] << std::endl;
      }
      
   }
   
};

If static constexpr is removed from the declaration, it compiles and runs.

The question is, why does declaring an array static constexpr seem to prevent local variables from being used to access it's members? The variable is local to the function and doesn't need any runtime information. And a constexpr array should be accessible at runtime anyway (it just doesn't change).

Upvotes: 0

Views: 79

Answers (1)

Jarod42
Jarod42

Reputation: 217135

"Hardcoded values work".

In fact no, clang spots the issue Demo

In all cases, aIvoryKeys is ODR-used and so need a definition.

C++17 makes aIvoryKeys inline, and resolves that issue.

Upvotes: 2

Related Questions