Recently, my teacher said that array initialization in C occurs in two ways:
- In the manual style
int a[5]={1,2,3,4,5}; - Use
scanf()asint a[5], i; for(i=0;i<5;i++) scanf("%d", &a[i]);
In my opinion, the second "path" is the assignment method, not the initialization. So I decided to check what people here can say about it. I came across this one where one answer states:
If all you ask is terminology (*, which is not entirely clear from your question), the "Initialization" of a variable is, literally, the first time it is assigned a value. This term comes from the fact that you give the variable this "initial" value.
This should (obviously) happen before it is used for the first time.
int x=5; is an announcement and initialization, and it's really just a convenient shortened version for
int x; x=5;
If I follow what this particular answer states, then the second way to “initialize” is correct, because no value scanf()has been assigned before the expression . However, thanks to my knowledge of static variables, a new doubt arises in my mind. Consider the following code:
#include <stdio.h>
void first_way(){
static int x[2]={1,2};
printf("first_way called %d time(s)\n",++x[0]);
}
void second_way(){
int i;
static int x[2];
for(i=0;i<2;i++)scanf("%d",&x[i]);
printf("second_way called %d time(s)\n",++x[0]);
}
int main(void){
int i;
for(i=0;i<3;i++)
first_way();
printf("\n#######\n");
for(i=0;i<3;i++)
second_way();
return 0;
}
His output looks like this:
first_way called 2 time(s)
first_way called 3 time(s)
first_way called 4 time(s)
1 2
second_way called 2 time(s)
1 2
second_way called 2 time(s)
1 2
second_way called 2 time(s)
This conclusion again makes me think of the version scanf()as an assignment version rather than initializing it, even if scanf()no value was assigned to the elements before the expression x[]. Return to the square.
So, the second version is really initialization, for example, my instructor or just an appointment (what I think)?
Edit:
, - , , static , static 0 , . - const.
const int x = 2; x, . , ( ):
int x = 5; - , int x; x=5;
, , scanf() ?