Arrays with a size determined at runtime, is this really in C ++?

So, I was talking with my friend, helping her with a piece of code, and I always thought that arrays should be compile-time constants, since they are on the stack. But she said her friend did this using this code:

#include <iostream.h>
#include <stdlib.h>
int main()
{
    int value = ' ' ;
    int sum = 0;
    int count = 0;
    cout<<"Please enter the total number of employees" <<endl;;
    cin>> value;
    int numbers[value];
    cout<<"Now enter the employees corresponding salaries" <<endl;;
    for (int k = 0; k < value; k++)
    {
        cin >> numbers[k];
    }
}

They use Dev-C ++.

Should this code work? I guess not.

+5
source share
4 answers

Variable length masks are an extension in gccand g++... therefore this will not work in every compiler.

For more support information gccfor variable-length arrays, you can see here.

+9
source
+4
#include <iostream.h>

^ . , 1998 . , , Visual ++.

cin>> value;
int numbers[value];

VLA C99 ++. ++, , , ++ 11. , , std::vector vector - .

g++ . . .

d:\dev\test> g++ foo.cpp

d:\dev\test> g++ -pedantic -std=c++0x -Wall -O foo.cpp
foo.cpp: In function 'int main()':
foo.cpp:11: warning: ISO C++ forbids variable length array 'numbers'
foo.cpp:7: warning: unused variable 'sum'
foo.cpp:8: warning: unused variable 'count'

d:\dev\test> _
+2

GCC 4.6 , , , . , , , .

0

All Articles