LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   const? (https://www.linuxquestions.org/questions/programming-9/const-476244/)

kalleanka 08-22-2006 10:15 AM

const?
 
why cant I do this:

const int i = 1;

char *myarr[i];

I get error: variable-size type declared outside of any function

I am used to pascal and how do I get a constant in c? Do I need to use the preprocessor?

dmail 08-22-2006 10:25 AM

that shouldn't throw any errors?
try it on it's own to see if it is this that is causing the error.
Quote:

int main()
{
const int i = 1;
char *myarr[i];
}

kalleanka 08-22-2006 10:36 AM

That works but I want it outside a function.

like this.

const int i = 1;
char *myarr[i];

int main()
{
return 0;
}


and then I get error: variable-size type declared outside of any function

kalleanka 08-22-2006 10:40 AM

Maybe: const char *myarr[i];

noop did not work.


I want to write genetric code. I need an array of widgets so I can add currencies in the future just by adding the name and/or number. I do not want to go in to the code and add a widget here and there.

dmail 08-22-2006 10:41 AM

I don't see a problem with that either??
VS doesn't have a problem.I'll just boot up nix an and see if it compiles.

[edit]This seems to be C specific problem (I missed that in your first post), I didn't know of a difference in C and C++ in this respect. hmmm.

kalleanka 08-22-2006 10:52 AM

Well gcc givs:

Desktop]$ gcc -Wall test.c -o test
test.c:2: error: variable-size type declared outside of any function

I think this is strange.


But this works

#define i 1
const char *myarr[i];
int main()
{
return 0;
}


now I only have to figuerout how I can use these in diffrent files.

kalleanka 08-22-2006 10:55 AM

You are probebly rigth that it works in C++. Its bigger diffencies between the two than I thougth now when I learnt some c.

dmail 08-22-2006 11:05 AM

http://www.linuxtopia.org/online_boo...ter08_005.html

RRR now I remember all the #defines I used in C.
If the value is needed for more than just the array size then use a define (but change the name from i to array_size or something). Else just char * myarr[1];

xhi 08-22-2006 11:09 AM

Quote:

Originally Posted by kalleanka
#define i 1
const char *myarr[i];
int main()
{
return 0;
}

the reason it works is because it is no longer a variable size array, when you compile i is replaced with 1. so what you have there is the same to the compiler as saying

const char *myarr[1];

while what you had originally seems like it should work (i though so anyhow), i just looked it up and it is not c standard to declare a variable size array globally like that.
Quote:

ISO C - 6.7.5.2
Only an ordinary identifier (as defined in 6.2.3) with both block scope or function
prototype scope and no linkage shall have a variably modified type.

kalleanka 08-22-2006 11:10 AM

Thanks dmail


All times are GMT -5. The time now is 11:28 PM.