1

I'm not sure why the error happened. However, in the following line the code is OK when compiling.

Does someone have any explanation?

#include <stdio.h>
int g_value = 10;
const int* p1 = &g_value;
const int* p2 = p1; // error: initializer element is not constant
int main()
{
    const int* p3 = &g_value;
    const int* p4 = p3; // Compile normally without any error!
    
    return 0;
}
Perlman Soong
  • 111
  • 1
  • 9
  • Yes, the rules for initializers of block-scope variables are different from the rules for initializers of file-scope variables. The former are required to be constant expressions, as C defines that term. The latter are not. In the code given, `p1` is not a constant expression. – John Bollinger Jan 12 '23 at 14:48
  • Could you give me more details? Or some links about this topic :-) – Perlman Soong Jan 12 '23 at 14:51
  • Have you considered simply pasting the error message into your search bar and seeing what your favorite search engine will tell you? – John Bollinger Jan 12 '23 at 14:52
  • 1
    @JohnBollinger Well, it's really the storage duration that matters. – Ian Abbott Jan 12 '23 at 14:52
  • Yes, @IanAbbott, that is true. If I intended to post an actual answer to this question then I would be more careful there. – John Bollinger Jan 12 '23 at 14:54
  • The `const` is a bit of a red-herring here. You can remove the `const` qualifiers from the file-scope variables and it will still fail. – pmacfarlane Jan 12 '23 at 14:55

0 Answers0