4

I read that array size needs to be known at compile-time. However, when I do this, it compiles and runs just fine without giving any errors...how come?

#include <iostream>

int main() {
    int size;
    std::cout << "Enter size: ";
    std::cin >> size;
    int a[size];

    return 0;
}
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Southee
  • 69
  • 3
  • 2
    [Variable length arrays are supported by many compilers as an extension](http://stackoverflow.com/q/21273829/1708801) but they are really a C99 feature standard C++ does not support them in general `std::vector` is the replacement. Using `-pedantic` should generate a warning. – Shafik Yaghmour Feb 19 '15 at 21:26
  • Recommend, if you are in C++ use the std container: vector, map, list, etc... – NetVipeC Feb 19 '15 at 21:27
  • Wow, I better not read old editions of any book from now on. So, is this a 100% safe practice? – Southee Feb 19 '15 at 21:29
  • Safe as in it is supported extension but it is not portable, for example Visual Studio does not support it. – Shafik Yaghmour Feb 19 '15 at 21:32
  • @Southee: It's not about the book being old, but about the book obviously not teaching standard C++ but some dialect. – Deduplicator Feb 19 '15 at 21:35

2 Answers2

6

You aren't compiling it as strictly conforming C++, but using an extension borrowed from C99.

Use -Wall -Wextra -pedantic -std=c++14 to make the compiler complain.
And remember that a conforming compiler only needs to output a single diagnostic on encountering a construct the standard deems ill-formed.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • Well, if it's no longer an issue, why would we want the compiler to complain? – Southee Feb 19 '15 at 21:31
  • If you are content with depending on $extension and thus limiting portability, by all means go ahead and ignore it. But you should at least be aware that you aren't writing standard C++ anymore. – Deduplicator Feb 19 '15 at 21:32
  • Hmmm...fair enough. Just like using namespace std, right? It's acceptable but not ideal. – Southee Feb 19 '15 at 21:37
  • Rather it's generally not a good idea, but sometimes worth it. Though [less for your second example](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice), and for Knuth sake [keep it out of headers](http://stackoverflow.com/questions/3186226/why-shouldnt-i-put-using-namespace-std-in-a-header). – Deduplicator Feb 19 '15 at 21:45
0

Variable length arrays are a reality in C++ and apparently also in C.

https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html

Mike Nakis
  • 56,297
  • 11
  • 110
  • 142
  • It depends by what you mean "safe". One would say that if the majority of compilers do not support it, then it is not safe. And as far as I know, not many compilers besides gcc have support for it at the moment. – Mike Nakis Feb 19 '15 at 21:30
  • Yeah, in that case, it's not safe. Thanks – Southee Feb 19 '15 at 21:38