constant size for arrays

May 26, 2009 at 8:25pm
Hi guys

the size of an array must be known before compilation right?
so why does this code work?
is my compiler making it work by allocating dynamic memory or what?

1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;

int main(int argc, char **argv)
{
    int i = atoi(argv[1]);
    int a[i];
    return 0;
}


the funny thing is that if I make it a global array
it does give an error if I use a non constant expression

thanks in advance
May 26, 2009 at 8:43pm
ISO C++ forbids variable size arrays.

Whether you get a warning/error about it during compiling can depend on the Warning Level
you have set.

MSVC will always treat it as an ERROR.

MINGW can let it pass (depending on warning level) - (Which it shouldn't in my opinion)
May 26, 2009 at 9:07pm
I see, trouble is error or not the thing works, I tried with several
numbers as arguments to the program and the array is allocated normally
I put some values in it and printed them back and it didn't give me a "segmentation fault" error
besides what is the size that is actually being used? I mean it can't be the one I give since is not
dynamic memory, can it possibly be using a default large size?

but thanks for your reply
May 26, 2009 at 9:42pm
here you go (are you using mingw or GCC/G++ compiler)
http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html
May 26, 2009 at 9:51pm
Just so you know, C++ doesn't allow it because it's a branch of C89, which didn't allow it. C99, which was publish one year after the current C++ standard, later allowed variable-sized stack arrays, and some compilers (to my knowledge, only GCC) added it to C++ as a non-standard extension.

Remember that just because a compiler allows it, it doesn't mean it's standard.
May 26, 2009 at 10:04pm
closed account (z05DSL3A)
C99, which was publish one year after the current C++ standard,

C99 was published a year after C++03?

Edit: I suppose C++98 is still 'current' as 2003 was a technical corrigendum.
Last edited on May 26, 2009 at 10:17pm
May 27, 2009 at 1:37pm
Thanks guys.

Is there a way of making my compiler accept only standard code?
I am using Code::Blocks on Ubuntu and it uses gcc.
May 27, 2009 at 2:26pm
IIRC, the compiler option was -pedantic.
May 27, 2009 at 5:42pm
Yeah, now it gives the warning:

main.cpp: In function ‘int main(int, char**)’:
main.cpp:7: error: ISO C++ forbids variable-size array ‘a’

thanks helios
Topic archived. No new replies allowed.