Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Constants and aggregates inside function body vs. outside

Consider the following piece of code:

#include <iostream>
using namespace std;

int main()
{
    int x = 3;
    const int i[] = { 1, 2, 3, 4 };
    float f[i[3]]; 
    struct S { int i, j; };
    const S s[] = { { 1, 2 }, { 3, 4 } };
    double d[s[1].j];
}

It runs without error. However, the following:

#include <iostream>
using namespace std;


int x = 3;
const int i[] = { 1, 2, 3, 4 };
float f[i[3]]; // error: array bound is not an integer constant before ']' token|
struct S { int i, j; };
const S s[] = { { 1, 2 }, { 3, 4 } };
double d[s[1].j]; // error: array bound is not an integer constant before ']' token|

int main()
{
    return 0;
}

Does not, as it gets the errors that are highlighted as comments. Can anyone explain to me why that is?

like image 465
George Cernat Avatar asked Aug 29 '17 19:08

George Cernat


People also ask

Why is Constexpr over const?

Like const , it can be applied to variables: A compiler error is raised when any code attempts to modify the value. Unlike const , constexpr can also be applied to functions and class constructors. constexpr indicates that the value, or return value, is constant and, where possible, is computed at compile time.

Does constexpr imply const?

The constexpr specifier declares that it is possible to evaluate the value of the function or variable at compile time. Such variables and functions can then be used where only compile time constant expressions are allowed. constexpr implies const.

Where are Constexpr variables stored?

Everyone knows the memory location tables of C and C++ programs. For operating systems, executable code and all the static variables get copied from the hard drive disc into the allocated areas of text, static ect. in the RAM.

Should constants be capitalized C++?

I know, that for C++ and Java it is a well established naming convention, that constants should be written all uppercase, with underscores to separate words. Like this (Java-example): public final static Color BACKGROUND_COLOR = Color.


1 Answers

More than likely, the reason the compiler allows it within the function is due to a compiler extension: variable-length arrays. They allow arrays declared inside of functions to have non-constexpr lengths. But it only works inside of functions, not at global scope.

like image 72
Nicol Bolas Avatar answered Oct 25 '22 00:10

Nicol Bolas