Link to home
Start Free TrialLog in
Avatar of kaufmed
kaufmedFlag for United States of America

asked on

Question About Array Initliazation

I'm compiling C code under Lucid Ubunutu using GCC version 4.4.3. I understand that a constant value must be used inside the brackets, and I thought that macros were considered constant since they are replaced by the precompiler. I am curious as to why the following doesn't seem to work under the aforementioned compiler.

#define ARRAY_SIZE 3
int arr[ARRAY_SIZE] = { 1, 2, 3 };

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of phoffric
phoffric

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of kaufmed

ASKER

Hmm...  I can't seem to reproduce it now (I've been making changes since I originally encountered the problem). If I recall correctly, it was complaining about too many initializers, but I only had the three, that's why I was confused.
Avatar of phoffric
phoffric

Well, if I make the macro 2 with three initializers, I got this: warning: excess elements in array initializerDo you think you may have had a mismatch earlier?
I usually go with   int arr[] = { 1, 2, 3 };when using initializers. Then if I add an extra initializer, I don't have to remember to change the marcro.But now you probably need to know how many elements are in the array:
    int num_elements = sizeof( arr ) / sizeof( arr[0] );

Open in new window

Avatar of kaufmed

ASKER

>>  Do you think you may have had a mismatch earlier?

It's entirely possible  :)

>>  I usually go with ...

I ended up going with the empty brackets after I found it mentioned somewhere online. I only use C for class projects, so I always end up forgetting what I learn about it (happens every semester!).

Thanks for confirming  :)
C is a language. I bet it took you more than one semester to learn your native language, right? If you use it a lot, you'll speak it fluently. Good luck with your studies.