Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining arrays with(out) constant expressions

Tags:

c++

c++11

I am slowly bringing myself up to c++11. I was looking at constexpr and stumbled into this wikipedia article which lead me to "something completely different". The basic example it gives is:

int get_five() {return 5;}
int some_value[get_five() + 7]; // Create an array of 12 integers. Ill-formed C++

It states "This was not legal in C++03, because get_five() + 7 is not a constant expression." and says that adding constexpr to the get_five() declaration solves the problem.

My question is "What problem?". I compiled that code with neither errors nor warnings. I played with it making it horribly non constant:

#include <iostream>

int size(int x) { return x; }

int main()
{
  int v[size(5) + 5];
  std::cout << sizeof(v) + 2 << std::endl;
}

This compiles with no complaints using:

g++ -Wall -std=c++03

and when executed I get the (correct) answer 42.

I admit that I generally use stl containers, not arrays. But I thought (and apparently so did wikipedia) that compilation of the above code would fail miserably. Why did it succeed?

like image 551
rpsml Avatar asked Dec 05 '25 13:12

rpsml


1 Answers

Variable-length arrays (that is, arrays whose size is determined by a non-constant expression) are allowed in C, and some C++ compilers allow them as an extension to the language. GCC is one such compiler.

You'll get a warning if you compile with -pedantic or -Wvla, or an error with -pedantic-errors. Use those flags if you want to avoid non-standard compiler extensions.

like image 95
Mike Seymour Avatar answered Dec 07 '25 02:12

Mike Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!