Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-const declaration of array

I have been teaching myself programming for couple of years, and I was sure that if you need array declaration of a variable number you need to use malloc or new.

Today I found that this compiles under g++ version 4.4.4, without warnings or errors:

#include <iostream>
using namespace std;

int main()
{
    int size_array;
    cin >> size_array;
    int iTable[size_array];

    for(int i=0;i < size_array;i++)
        iTable[i]=i*i;
    for(int i=0;i < size_array;i++)
        cout << iTable[i] << endl;

    return 0;
}

Also it compiles completely fine if you are using gcc (after changing cout and cin with printf and scanf)

Under Visual Studio this code fails to compile since size_array is not constant.

When this was changed? This is a safe method?

like image 232
Paweł Sołtysiak Avatar asked Mar 21 '11 12:03

Paweł Sołtysiak


People also ask

Can you declare an array as a constant?

Arrays are Not Constants It defines a constant reference to an array. Because of this, we can still change the elements of a constant array.

What is constant declaration in c++?

The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.

Why can't you assign a const reference to a non const reference?

because it immediately violates the rules of const-correctness. so what you are saying is that there is no implicit conversion taking place on x "from int to const int " during reference binding is that right? If yes can you provide link to the standard of the statement which proves your point..

Can you modify a const array C++?

You can't. The const keyword is used to create a read only variable. Once initialised, the value of the variable cannot be changed but can be used just like any other variable. That means, a const qualified variable must not be assigned to in any way during the run of a program.


3 Answers

This is a C99 feature - VLA - which is not a part of standard c++. You can use it if your compiler supports it and you don't require portability. If the compiler supports it, it's perfectly safe to use - but it's a bad habit using non-standard features.

like image 54
Erik Avatar answered Nov 10 '22 07:11

Erik


This is a compiler extension of gcc, not standard.

like image 29
Jon Avatar answered Nov 10 '22 07:11

Jon


No thats not safe at all. It could corrupt your stack.

like image 2
Daniel A. White Avatar answered Nov 10 '22 08:11

Daniel A. White