Array initialization with non constant expression

For everyone, just starting with C++ or programming at all. Ask newbie questions in this forum!

Moderators: Darobat, RecursiveS, Dante Shamest, Bugdude, Wizard

Array initialization with non constant expression

Postby Mefisto » Sat Aug 29, 2009 3:13 am

Hi all,
you know the Stroustrup says:"..you cannot initialize an array with a non constant expression" or something like this.
Well, i'm on a mac and i use XCode to compile my c++ projects.
Can you explain me why the hell i'm able to compile without ANY errors and with the correct output, the following code??

Code: Select all
#include <iostream>

int main()
{
     int size;

     std::cin >> size;
     int array[size];

     array[0] = size;//just to test
     std::cout << array[0];
}



Thanks
Mefisto
 
Posts: 2
Joined: Sat Aug 29, 2009 3:04 am

Re: Array initialization with non constant expression

Postby Alvaro » Sat Aug 29, 2009 5:56 pm

Some compilers allow arrays with run-time size, but the standard doesn't require them to. Your code won't work in other compilers.

I believe XCode uses gcc under the hood. If that is the case, you can try passing option `-pedantic', which will make it complain about something like this.
User avatar
Alvaro
Moderator
 
Posts: 5185
Joined: Mon Sep 22, 2003 4:57 pm
Location: NY, USA

Re: Array initialization with non constant expression

Postby Mefisto » Sun Aug 30, 2009 1:57 am

Yes It uses gcc,
so thanks for your clean and full answer!
Mefisto
 
Posts: 2
Joined: Sat Aug 29, 2009 3:04 am

Re: Array initialization with non constant expression

Postby jlou » Sun Aug 30, 2009 7:42 pm

Note that it's called a variable length array (VLA) and allowed in C99, which is why gcc allows it as an extension for C++ programs. It's not allowed in standard C++.
User avatar
jlou
 
Posts: 760
Joined: Tue Sep 21, 2004 6:42 pm

Re: Array initialization with non constant expression

Postby GiovaMaster » Tue Sep 01, 2009 9:41 am

thanks for your specification jlou!
The essence is the problem, and the algorithm is in me
User avatar
GiovaMaster
 
Posts: 168
Joined: Sun May 23, 2004 2:53 am
Location: Florence, Italy


Return to For Beginners

Who is online

Users browsing this forum: No registered users and 1 guest