My instructor recently told that array initialization in C happens in two ways, namely:
- Manually like
int a[5]={1,2,3,4,5};
- Using
scanf()
like int a[5], i; for(i=0;i<5;i++) scanf("%d", &a[i]);
In my opinion the second "way" is a way of assignment and not initialization. So I decided to check what people over here have to say about this. I stumbled upon this post where one answer claims:
If all you are asking about is terminology (*which isn't really clear
from your question), "Initialization" of a variable is, literally, the
first time a value is assigned to it. This term comes from the fact
that you are giving the variable it's "initial" value.
This should (obviously) happen before it is used the first time.
int x=5;
is a declaration and an initialization, and is really just
convenient shorthand for
int x; x=5;
If I'm to follow what this particular answer claims, then the second way of "initialization" is correct, because no value was assigned prior to the scanf()
statement. However, thanks to my knowledge on 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)
",++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)
",++x[0]);
}
int main(void){
int i;
for(i=0;i<3;i++)
first_way();
printf("
#######
");
for(i=0;i<3;i++)
second_way();
return 0;
}
Its output is 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 output again leads me to think of scanf()
version more like an assignment version rather than initialization even though no value to elements of x[]
were assigned before the scanf()
statement. Back to square one.
So, is the second version really an initialization like my instructor claims or merely an assignment (which is what I believe)?
Edit:
After someone pointed out, I feel my static
array example is a poor one as static
variables are implicitly initialized to 0 no matter what. Then again, someone else pointed me towards const
variables.
Consider const int x = 2;
Here one can initialize x
, but cannot assign any value to it after initialization. But this is conflicting with the answer that claims (I quote it again):
int x = 5;
is a declaration and an initialization, and is really just
convenient shorthand for int x; x=5;
So, after all this, does the scanf()
version qualify as an initializer?
See Question&Answers more detail:
os