static int number[3] = { 5, 7, 2 }; // 100% correct syntax. volatile int a; int i; for ( i = 0 ;i < 3 ;++i) a = numbers[i]; // also this works, if you don't feel like counting int numbers[]={1,2,3}; // if you need to know how many are in it: int a = sizeof(numbers)/sizeof(int); // this is calculated at compile time. // Just wondering, why did you use static? (a quiz)
// This code works fine.// Did you call the function and step into it? // If you never call the function, then the compiler won't bother // putting any if there. void Initialize_variables(void){static int number[3] = {1,2,3}; volatile int a; int i; for (i = 0 ;i < 3 ;++i) a = number[i];}
// The first meaning of static - limiting scope.static int a; // only code in this file can see 'a'int b; // any file linked into this program and see b.void (void){ // example of funcction scope. int c; // only code in this function and see 'c'}
int* f(void){ int a=0; // created on the static. goes away when I leave this function. static int b=0; // created in ram - keeps it's value. a = 1; // The next time I call the function, a will be 0 b = 1; // b will still be 1. return &b; // ok - lets the caller see b. return &a; // error - this would be a terrible mistake // and will result in a crash or other odd bugs. (you wouldn't really have two returns, just for illustration) }
JimDon wrote:The second meaning of static is within a function. Normally variables declared in a function are "automatic" this means they are created on the stack and go away when you leave the function.
When you declare a variable static in a function, it is no longer on the stack and is placed in ram or rom and retains it's value across function calls. However, it's scope is still for that function only.
You can however return a pointer to it so other code could see it.
int a=0; // created on the static. goes away when I leave this function.
int a=0; // created on the *stack*. goes away when I leave this function.