473,394 Members | 1,702 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

variable as an array size

Hi,

I'm wondering what you think about this piece of code:

#include<iostream>

int main()
{
int size;
std::cin >> size;
int array[size];

std::cout<<sizeof(int)<<" "<<sizeof(array);
return 0;
}

Is it legal or not (according to C/C++ standard)?
A couple of days ago I would say it is not, only constant expression can
be used to specify the size, of the array, but now I'm not sure :) The
reason is that gcc 3.4.4 compiles at with no errors and warnings.
And the result printed by the program is correct:

sizeof(arr) = size * sizeof(int)

P.S.
MS Visual C++ 7.1 does not compile this code. It gives the following errors:
main.cpp(7) : error C2057: expected constant expression
main.cpp(7) : error C2466: cannot allocate an array of constant size 0
main.cpp(7) : error C2133: 'array' : unknown size
main.cpp(9) : error C2070: 'int []': illegal sizeof operand
Oct 12 '05 #1
13 21328
HappyHippy wrote:

Hi,

I'm wondering what you think about this piece of code:

it uses an gcc extension.
A couple of days ago I would say it is not, only constant expression can
be used to specify the size,


As for now, you are correct.

--
Karl Heinz Buchegger
kb******@gascad.at
Oct 12 '05 #2
I really don't like this unnecessary extension. I tried to turn on
some flags to force gcc to treat it as an error. But all I got so far
is an warning with -pedantic. Is there any way to escalate it to
error? Thanks.

[nan@xxx test]$ cat ary.c
int main()
{
int size;
int array[size];
return 0;
}

[nan@xxx test]$ gcc -pedantic ary.c
ary.c: In function `main':
ary.c:4: warning: ISO C89 forbids variable-size array `array'

[nan@xxx test]$ gcc -Wall -ansi -std=c89 ary.c
ary.c: In function `main':
ary.c:4: warning: unused variable `array'

[nan@xxx test]$ gcc -v
Reading specs from /usr/lib/gcc-lib/i386-redhat-linux/3.2.3/specs
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man
--infodir=/usr/share/info --enable-shared --enable-threads=posix
--disable-checking --with-system-zlib --enable-__cxa_atexit
--host=i386-redhat-linux
Thread model: posix
gcc version 3.2.3 20030502 (Red Hat Linux 3.2.3-20)

Oct 12 '05 #3
Karl Heinz Buchegger wrote:
HappyHippy wrote:

Hi,

I'm wondering what you think about this piece of code:


it uses an gcc extension.
A couple of days ago I would say it is not, only constant expression can
be used to specify the size,


As for now, you are correct.

--
Karl Heinz Buchegger
kb******@gascad.at

I really don't like this unnecessary extension. I tried to turn on
some flags to force gcc to treat it as an error. But all I got so far
is an warning with -pedantic. Is there any way to escalate it to
error? Thanks.

[nan@xxx test]$ cat ary.c
int main()
{
int size;
int array[size];
return 0;
}

[nan@xxx test]$ gcc -pedantic ary.c
ary.c: In function `main':
ary.c:4: warning: ISO C89 forbids variable-size array `array'

[nan@xxx test]$ gcc -Wall -ansi -std=c89 ary.c
ary.c: In function `main':
ary.c:4: warning: unused variable `array'

[nan@xxx test]$ gcc -v
Reading specs from /usr/lib/gcc-lib/i386-redhat-linux/3.2.3/specs
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man
--infodir=/usr/share/info --enable-shared --enable-threads=posix
--disable-checking --with-system-zlib --enable-__cxa_atexit
--host=i386-redhat-linux
Thread model: posix
gcc version 3.2.3 20030502 (Red Hat Linux 3.2.3-20)

Oct 12 '05 #4
In article <di**********@charm.magnus.acs.ohio-state.edu>,
HappyHippy <ka******@mail.ru> wrote:
I'm wondering what you think about this piece of code:

#include<iostream>

int main()
{
int size;
std::cin >> size;
int array[size];

std::cout<<sizeof(int)<<" "<<sizeof(array);
return 0;
}

Is it legal or not (according to C/C++ standard)?
It is not legal C++.
It is not legal C90.
It is legal C99.
A couple of days ago I would say it is not, only constant expression can
be used to specify the size, of the array, but now I'm not sure :) The
reason is that gcc 3.4.4 compiles at with no errors and warnings.
And the result printed by the program is correct:

sizeof(arr) = size * sizeof(int)

P.S.
MS Visual C++ 7.1 does not compile this code. It gives the following errors:
main.cpp(7) : error C2057: expected constant expression
main.cpp(7) : error C2466: cannot allocate an array of constant size 0
main.cpp(7) : error C2133: 'array' : unknown size
main.cpp(9) : error C2070: 'int []': illegal sizeof operand


If a compiler supports C99 or at least C99's VLA (variable length array)
features, or some similar extension, then it'll work with that compiler.
--
Greg Comeau / Celebrating 20 years of Comeauity!
Comeau C/C++ ONLINE ==> http://www.comeaucomputing.com/tryitout
World Class Compilers: Breathtaking C++, Amazing C99, Fabulous C90.
Comeau C/C++ with Dinkumware's Libraries... Have you tried it?
Oct 12 '05 #5
There were a lot of discussions at comp.lang.c back in 2003.
http://groups.google.com/group/comp....6113459b9beb6d

Also more clear explanation here.
http://developer.apple.com/documenta...le-Length.html

After reading the above, I think it is actually quite a good feature to
have.

Nan
Greg Comeau wrote:
In article <di**********@charm.magnus.acs.ohio-state.edu>,
HappyHippy <ka******@mail.ru> wrote:
I'm wondering what you think about this piece of code:

#include<iostream>

int main()
{
int size;
std::cin >> size;
int array[size];

std::cout<<sizeof(int)<<" "<<sizeof(array);
return 0;
}

Is it legal or not (according to C/C++ standard)?


It is not legal C++.
It is not legal C90.
It is legal C99.
A couple of days ago I would say it is not, only constant expression can
be used to specify the size, of the array, but now I'm not sure :) The
reason is that gcc 3.4.4 compiles at with no errors and warnings.
And the result printed by the program is correct:

sizeof(arr) = size * sizeof(int)

P.S.
MS Visual C++ 7.1 does not compile this code. It gives the following errors:
main.cpp(7) : error C2057: expected constant expression
main.cpp(7) : error C2466: cannot allocate an array of constant size 0
main.cpp(7) : error C2133: 'array' : unknown size
main.cpp(9) : error C2070: 'int []': illegal sizeof operand


If a compiler supports C99 or at least C99's VLA (variable length array)
features, or some similar extension, then it'll work with that compiler.
--
Greg Comeau / Celebrating 20 years of Comeauity!
Comeau C/C++ ONLINE ==> http://www.comeaucomputing.com/tryitout
World Class Compilers: Breathtaking C++, Amazing C99, Fabulous C90.
Comeau C/C++ with Dinkumware's Libraries... Have you tried it?


Oct 12 '05 #6
Greg Comeau wrote:

It is not legal C++.
It is not legal C90.
It is legal C99.
If a compiler supports C99 or at least C99's VLA (variable length
array) features, or some similar extension, then it'll work with that
compiler.

Greg is (as always) correct. I seem to recall that the C++ committee
was reviewing VLAs for possible inclusion, but I don't know whether
that's actually the case.

It isn't as important in C++, because one can use std::vector in most
cases where a VLA would be used.

Brian
Oct 12 '05 #7
Default User wrote:
It isn't as important in C++, because one can use std::vector in most
cases where a VLA would be used.
The problem with introducing variable sized arrays, I would guess is
the fact that one may run out of stack more easily. However, allocation
on the stack is re-entrant, does not require overhead concerned with
heap allocation etc. IMHO it would be good if the standards comittee
would introduce a new type - specifically for this purpose. Let arrays
still have fixed sizes - no suprises. If one wants variable sized
arrays, be aware that they are allocated on the stack only... You think
this is possible/plausible?

Regards,

W

Brian


Oct 12 '05 #8
In article <11**********************@g44g2000cwa.googlegroups .com>,
Nan Li <na******@gmail.com> wrote:
There were a lot of discussions at comp.lang.c back in 2003.
http://groups.google.com/group/comp....6113459b9beb6d
That thread started as a question about VLAs but except for the first
few messages, the rest has nothing to do with it.
Also more clear explanation here.
http://developer.apple.com/documenta...le-Length.html

After reading the above, I think it is actually quite a good feature to
have.


Maybe in C. Maybe. But C++ has alther alternatives, probably
better ones.

Oddly, it will be C++ that ends up popularizing C99 features.
I don't see that as good.
--
Greg Comeau / Celebrating 20 years of Comeauity!
Comeau C/C++ ONLINE ==> http://www.comeaucomputing.com/tryitout
World Class Compilers: Breathtaking C++, Amazing C99, Fabulous C90.
Comeau C/C++ with Dinkumware's Libraries... Have you tried it?
Oct 12 '05 #9
werasm wrote:
Default User wrote:
It isn't as important in C++, because one can use std::vector in
most cases where a VLA would be used.


The problem with introducing variable sized arrays, I would guess is
the fact that one may run out of stack more easily. However,
allocation on the stack is re-entrant, does not require overhead
concerned with heap allocation etc. IMHO it would be good if the
standards comittee would introduce a new type - specifically for this
purpose. Let arrays still have fixed sizes - no suprises. If one
wants variable sized arrays, be aware that they are allocated on the
stack only... You think this is possible/plausible?


If they do anything, I suspect it will be the same as C99.

Brian

Oct 12 '05 #10
In article <3r************@individual.net>,
Default User <de***********@yahoo.com> wrote:
werasm wrote:
Default User wrote:
> It isn't as important in C++, because one can use std::vector in
> most cases where a VLA would be used.


The problem with introducing variable sized arrays, I would guess is
the fact that one may run out of stack more easily. However,
allocation on the stack is re-entrant, does not require overhead
concerned with heap allocation etc. IMHO it would be good if the
standards comittee would introduce a new type - specifically for this
purpose. Let arrays still have fixed sizes - no suprises. If one
wants variable sized arrays, be aware that they are allocated on the
stack only... You think this is possible/plausible?


If they do anything, I suspect it will be the same as C99.


There is really no other incentive, except as C99 compatibilty,
at best, so yeah, if possible.
--
Greg Comeau / Celebrating 20 years of Comeauity!
Comeau C/C++ ONLINE ==> http://www.comeaucomputing.com/tryitout
World Class Compilers: Breathtaking C++, Amazing C99, Fabulous C90.
Comeau C/C++ with Dinkumware's Libraries... Have you tried it?
Oct 12 '05 #11
Nan Li wrote:
I really don't like this unnecessary extension. I tried to turn on
some flags to force gcc to treat it as an error. But all I got so far
is an warning with -pedantic. Is there any way to escalate it to
error? Thanks.

int main()
{
int size;
int array[size];
return 0;
}

[nan@xxx test]$ gcc -pedantic ary.c
ary.c: In function `main':
ary.c:4: warning: ISO C89 forbids variable-size array `array'

[nan@xxx test]$ gcc -Wall -ansi -std=c89 ary.c
ary.c: In function `main':
ary.c:4: warning: unused variable `array'


$ g++ -o x x.c -Wall -Wextra -ansi -pedantic
x.c: In function `int main()':
x.c:5: error: ISO C++ forbids variable-size array `array'

<OT reason="we are in comp.lang.c++">
The C standard only specifies that invalid code generates
a diagnostic message. So GCC is conforming when it issues
the warning. In GCC you can escalate the warning with the
-pedantic-errors switch.

Note also that -ansi and -std=c89 mean the same thing,
you only need one or the other.

$ gcc -o x x.c -Wall -Wextra -ansi -pedantic-errors
x.c: In function `main':
x.c:5: error: ISO C90 forbids variable-size array `array'
x.c:5: warning: unused variable `array'

</OT>

Oct 12 '05 #12
Greg Comeau wrote:
In article <3r************@individual.net>,
Default User <de***********@yahoo.com> wrote:

> It isn't as important in C++, because one can use std::vector in
> most cases where a VLA would be used.
If they do anything, I suspect it will be the same as C99.


There is really no other incentive, except as C99 compatibilty,
at best, so yeah, if possible.


Easier on the implementors not to have yet another version of VLAs as
well.
Brian
Oct 12 '05 #13
On 12 Oct 2005 09:13:54 -0700, "Nan Li" <na******@gmail.com> wrote in
comp.lang.c++:

Top-posting is considered rude in this, and many other technical
newsgroups. It makes technical discussions very hard to follow. I
have reformatted your post and added my comments at the end.
Greg Comeau wrote:
In article <di**********@charm.magnus.acs.ohio-state.edu>,
HappyHippy <ka******@mail.ru> wrote:
I'm wondering what you think about this piece of code:

#include<iostream>

int main()
{
int size;
std::cin >> size;
int array[size];

std::cout<<sizeof(int)<<" "<<sizeof(array);
return 0;
}

Is it legal or not (according to C/C++ standard)?


It is not legal C++.
It is not legal C90.
It is legal C99.
A couple of days ago I would say it is not, only constant expression can
be used to specify the size, of the array, but now I'm not sure :) The
reason is that gcc 3.4.4 compiles at with no errors and warnings.
And the result printed by the program is correct:

sizeof(arr) = size * sizeof(int)

P.S.
MS Visual C++ 7.1 does not compile this code. It gives the following errors:
main.cpp(7) : error C2057: expected constant expression
main.cpp(7) : error C2466: cannot allocate an array of constant size 0
main.cpp(7) : error C2133: 'array' : unknown size
main.cpp(9) : error C2070: 'int []': illegal sizeof operand


If a compiler supports C99 or at least C99's VLA (variable length array)
features, or some similar extension, then it'll work with that compiler.
--
Greg Comeau / Celebrating 20 years of Comeauity!
Comeau C/C++ ONLINE ==> http://www.comeaucomputing.com/tryitout
World Class Compilers: Breathtaking C++, Amazing C99, Fabulous C90.
Comeau C/C++ with Dinkumware's Libraries... Have you tried it?


There were a lot of discussions at comp.lang.c back in 2003.
http://groups.google.com/group/comp....6113459b9beb6d

Also more clear explanation here.
http://developer.apple.com/documenta...le-Length.html

After reading the above, I think it is actually quite a good feature to
have.

Nan


No, actually it is a dangerous and hideously unsafe feature,
especially is used carelessly. My impression is that it was a hack to
those who insisted that they couldn't live without gcc's (and other
compiler's) alloca(). They couldn't possibly afford the performance
hit of calling malloc(), or new[] in C++.

If the variable value happens to be too large to be accommodated, VLAs
can just terminate your program. They are not required to give you an
error indication such as a NULL pointer or throwing an exception, so
you can decide what to do.

If you want to be sure you can detect an insufficient memory problem
and decide how to deal with it, you can't depend on VLAs, you must use
malloc() or new[].

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html

Oct 14 '05 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: dati_remo | last post by:
Hi, is it possible to find the dimension of an array using a pointer? main() { int a; f(a); return; }
4
by: terry | last post by:
Hi, Could anyone tell me how to determine the size of array of characters dynamically? For example, : : char *a={"hello","hi","kitty"}; char *b={"orange","apple"};
7
by: arkobose | last post by:
hey everyone! i have this little problem. consider the following declaration: char *array = {"wilson", "string of any size", "etc", "input"}; this is a common data structure used to store...
4
by: Bilgehan.Balban | last post by:
Hi, The following code: #include <stdio.h> // const int const_asize = 10; #define define_asize = 10; int array = {1,2,3,4,5,6,7,8,9,0};
6
by: echoking | last post by:
I have a program that asks a user for a integer. This integer is a member of a struct statement. Later on in the program a function points to this structure in hopes of using the integer as a...
2
by: axas | last post by:
Why on Windows we can' t declare an array with a variable for array's size? e.g. void func(int size) { int array; } On Linux systems we can do it.
2
by: Harry | last post by:
Good Day To all, When i am declaring a array for e.g char ....it means i am declaring array of 45 characters each of which has a maximum,minimum value limit or range...for example in...
8
by: s4tanu | last post by:
Hi, char arr_one = {'a','b','c','d','\0'}; i want to make another array with same size as 'arr_one' if i do like this - size_t len= strlen(arr); char arr_two;
0
by: PauloD | last post by:
public struct Character_Items { public short Armor; public short Helm; public short WeaponL; public short WeaponR; public short Pants; public short Boots; public short Gloves; public short...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.