473,626 Members | 3,459 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Specifying global array size with const int

Hi,

The following code:

#include <stdio.h>

// const int const_asize = 10;
#define define_asize = 10;

int array[define_asize] = {1,2,3,4,5,6,7, 8,9,0};

int main(int argc, char * argv[])
{

return 0;
}

Using the #define compiles with no errors, however if you replace it
with the constant variable, I get the following error:

"error: variable-size type declared outside of any function"
"error: variable-sized object may not be initialized"

this is on gcc compiling with the following: gcc -o consttest main.c
adding a -std=c99 does not make any difference.

So the compiler differentiates between a literal and a const int when
they're declared global, but make no distinction when they're local. My
question is, is this standard C behaviour? i.e. Has it been defined as
part of C to refuse to compile above code with a const int specifying
array size, when the array is declared global?

Thanks,
Bahadir

Nov 15 '05 #1
4 21699
<Bi************ *@gmail.com> wrote in message
news:11******** **************@ o13g2000cwo.goo glegroups.com.. .
....
// const int const_asize = 10;
#define define_asize = 10;

int array[define_asize] = {1,2,3,4,5,6,7, 8,9,0};

....

IMO, what you're trying to do is C++, which is not C.

Alex
Nov 15 '05 #2
Bi************* @gmail.com wrote on 01/09/05 :
Hi,

The following code:

#include <stdio.h>

// const int const_asize = 10;
#define define_asize = 10;

int array[define_asize] = {1,2,3,4,5,6,7, 8,9,0};
You don't need the size. The compiler can count the initializers and
size the array for you :

int array[] = {1,2,3,4,5,6,7, 8,9,0};

You can retreive the size by applying the definition of an array
(sequence of elements of the same size), hence :

size_t n = sizeof array / sizeof array[0];

or

size_t n = sizeof array / sizeof *array;

which is easily macroizable to the handy:

#define NELEM(a) (sizeof(a)/sizeof*(a))
int main(int argc, char * argv[])
{

return 0;
}

Using the #define compiles with no errors, however if you replace it
with the constant variable, I get the following error:

"error: variable-size type declared outside of any function"
"error: variable-sized object may not be initialized"
Yes. In C, the array sizer must be a constant expression
(C99 allows VLA under certain conditions. Note that today's
implementations of VLA are broken, even with gcc 4.x).
this is on gcc compiling with the following: gcc -o consttest main.c
adding a -std=c99 does not make any difference.
Obviously, VLA are not permitted on static arrays.
So the compiler differentiates between a literal and a const int when
they're declared global, but make no distinction when they're local. My
question is, is this standard C behaviour? i.e. Has it been defined as
part of C to refuse to compile above code with a const int specifying
array size, when the array is declared global?


Yes, it's conforming with C99.

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

"Clearly your code does not meet the original spec."
"You are sentenced to 30 lashes with a wet noodle."
-- Jerry Coffin in a.l.c.c++
Nov 15 '05 #3
Bi************* @gmail.com writes:
The following code:

#include <stdio.h>

// const int const_asize = 10;
#define define_asize = 10;

int array[define_asize] = {1,2,3,4,5,6,7, 8,9,0};

int main(int argc, char * argv[])
{

return 0;
}

Using the #define compiles with no errors,
No, it doesn't, but if you change the line
#define define_asize = 10;
to
#define define_asize 10
it does compile.

This isn't just nitpicking. If you post code to this newsgroup,
*please* cut-and-paste the actual code that you fed to the compiler;
don't try to re-type it. The more time we spend trying to distinguish
between a possible typo and whatever is actually causing the problem
you're asking about, the less time we can spend answering your
question.

(Incidentally, it's traditional for macro names to be in all-caps,
e.g.:

#define DEFINE_ASIZE 10
int array[DEFINE_ASIZE] = {1,2,3,4,5,6,7, 8,9,0};
however if you replace it
with the constant variable, I get the following error:

"error: variable-size type declared outside of any function"
"error: variable-sized object may not be initialized"

this is on gcc compiling with the following: gcc -o consttest main.c
adding a -std=c99 does not make any difference.
Right. The keyword "const" doesn't create a constant. It should
really be called something like "readonly". The way to create a true
constant is either to use #define, or, for a value that fits in an
int, an enum declaration:

enum { asize = 10 };
int array[asize] = {1,2,3,4,5,6,7, 8,9,0};

The latter is probably an abuse of enum types, but it's a fairly
common idiom.

The lack of a good way to create genuine constants in C is arguably a
flaw in the language, but we're stuck with it.
So the compiler differentiates between a literal and a const int when
they're declared global, but make no distinction when they're local. My
question is, is this standard C behaviour? i.e. Has it been defined as
part of C to refuse to compile above code with a const int specifying
array size, when the array is declared global?


It does distinguish between a literal and a const int in either
context. The difference is that variable length arrays (VLAs) are
legal in a local context. In the following:

int main(void)
{
#define TEN 10
const int ten = 10;
int arr0[TEN];
int arr1[ten];
...
}

arr0 is an ordinary array, but arr1 is a VLA. As you've seen, if
these declarations appeared outside a function, the declaration of
arr1 would be illegal, simply because you can't have global VLAs.

Note also that VLAs are a new feature in C99, and some compilers may
not yet implement them.

Finally, as someone else has pointed out, you don't need to specify the
size in this case; the size can be inferred from the initialization:

int array[] = {1,2,3,4,5,6,7, 8,9,0};

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #4
Keith Thompson wrote:
It does distinguish between a literal and a const int in either
context. The difference is that variable length arrays (VLAs) are
legal in a local context. In the following:

int main(void)
{
#define TEN 10
const int ten = 10;
int arr0[TEN];
int arr1[ten];
...
}

arr0 is an ordinary array, but arr1 is a VLA.
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.


Thank you, this clarified it for me very well. I won't post broken code
next time.

Regards,
Bahadir

Nov 15 '05 #5

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

Similar topics

14
3899
by: Gianni Mariani | last post by:
Does anyone know if this is supposed to work ? template <unsigned N> int strn( const char str ) { return N; } #include <iostream>
7
2409
by: news.hku.hk | last post by:
suppose i have a class abc, and i have an important value stored as int integer = 888; when i want to declare an array of objects: abc obj; // error said non-constant....expect constant array size....and the like What can i do if i really want 888 as the array size ???
12
2739
by: flipflop | last post by:
I need to create a global array whose dimensions depend on the contents of another global array populated at its initialisation. For example: int array1={3,2,1}; int array2]; //should be equiv. to: int array2; GCC gives these errors: variable-size type declared outside of any function variable-sized object may not be initialized
8
3507
by: chellappa | last post by:
hi Everybody ! decalaring variable in a.h and using that vaaariable in a1.c and inalization is in main.c it is possible .........pleaase correct that error is it Possible? i am trying it gives error! In file included from main.c:2: a1.c:3: error: initializer element is not constant
3
2689
by: danbraund | last post by:
Hi everyone, I'm a long time C coder, who is coding his final year project in C++ to run under the MIT click routing system. Being fairly new to the OO side of the language, my problem is this: In C++, how can I define a global array whose size is determined by parameters passed to a class? The array is of static size once defined, but the parameters of course arent read until the config function is called at class startup. is there a...
9
2151
by: barcaroller | last post by:
Can variables be used for array size in C++? I know that in the past, I could not do the following: foo (int x) { type arr; } I have recently seen code that does exactly that. Is it right?
1
1973
by: asit | last post by:
We know that array size can be a constant integer. Consider the following case ?? calss myc { const int size; int arr; public: myc(int x):size(x){}
10
24667
by: Chunekit Pong | last post by:
I have a BYTE array - BYTE const* pbBinary I would like to know how many bytes in that byte array but if I do - sizeof(* pbBinary); - then I got 1 but if I do - sizeof( pbBinary); - then I got 4 I am sure the array has hundreds of bytes
6
3938
MrPickle
by: MrPickle | last post by:
I have a struct like so defined like so: //vector3.h struct Vector3 { float x, y, z; Vector3(); Vector3(float _x, float _y, float _z); Vector3(const Vector3 &v); };
0
8202
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8510
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7199
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6125
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5575
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4093
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4202
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2628
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1812
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.