Can const variables be used to define an array's initial size?

Status
Not open for further replies.

electronics_guy

Member level 2
Joined
Apr 12, 2012
Messages
49
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,286
Activity points
1,655
Hi all,

What is wrong with the snippet:
Code:
const int a=5;
int b[a]={1,2,3,4,5};

The compiler always throws an error with the code above.

What could be the problem? Plz help


Thanks in advance
 

you can not use a variable as array size but It may be a macro


Code C - [expand]
1
2
3
#define a 5
 
int b[a]={1,2,3,4,5};



already a is constant by this method you are saving a variable space also....
 

Logically it seems that it should work. But i suppose it depends on your compiler how its handled.

You could instead "#define a" if you know what it is at compile time.....
 

Many compilers like GCC will allow to use this, but the array should not be initialized. Its values can be changed/assigned afterwards in the program.
 








In ubuntu GCC

 

Attachments

  • error.JPG
    53.2 KB · Views: 145
  • working.JPG
    39.7 KB · Views: 153
  • gcc.JPG
    46.5 KB · Views: 126
Last edited:

It is not compiler dependent It is c standard in all the compilers.

Which C standard are you referring to ? I did not realise that all compilers behaved in exactly the same way..... That would surely obviate the need for any variety in C compilers.
 

Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…