I made this code and tried:
int main(void) {
int vetor[10] = {0};
vetor[10] = {0}; //há um erro aqui mas compila em C++
return 0;
}
Compiling in C does not really work because C does not have extended initializers . The syntax of C allows this syntax to be used in the declaration but can not be used in later assignment, so it explains why the first one you mentioned gives problem and the second example of yours works. See in the ideone .
If you do the same thing using a modern C ++, at least C ++ 11, this feature is available and can be used. See on ideone . Note that the error message shows that you should use at least C ++ 11.
Understand that C and C ++ are different languages. And even the language version difference can change the result. You can not use what is not in the default, has not been invented yet or has not been implemented in the compiler you are using. In C there is no solution other than initializing the elements in the traditional way. In C ++ just choose to compile with the newer version available in GCC.
The solution actually only allows to zero the array at startup. Then you can allocate numbers on all elements through a loop. In this case it need not necessarily be a zero. Another option is to call the function memset()
which also only allows to zero all, after all it was made to work with strings and not numbers (actually the initialization of all array is internally replaced by memset()
). See correct examples:
#include <stdio.h>
#include <string.h>
int main(void) {
int vetor[10] = {0};
for (int i = 0; i < 10; i++) {
printf("%d", vetor[i]);
}
for (int i = 0; i < 10; i++) {
vetor[i] = 1;
}
for (int i = 0; i < 10; i++) {
printf("%d", vetor[i]);
}
memset(vetor, 0, sizeof(vetor));
for (int i = 0; i < 10; i++) {
printf("%d", vetor[i]);
}
return 0;
}
See running on ideone .
I get better if I have more details.