In the code: ...
#define MAXELEMNTS 100
struct book
{
int number;
char name[31];
char author[31];
int year;
char publisher[31];
};
struct book bkStruct[MAXELEMENTS];
...
Are the integer fields (number and year) initialized to 0 by default when the other char fields are initialized but not these two? Or do they have god-knows-what value? In my experience they do have value = 0, but I am not sure is this general rule so I must be sure!
Best regards, Papo
In C there is no such thing as "partial initialization". If a struct is initialized by specifying a value for a single member, all the other members are automagically initialized (to
0
of the proper kind).Note: some implementations may complain about missing braces on the perfectly legal array initialization. That is a problem with those implementations.
to be on safe side you should intialize your varibales to 0 yourself depending upon compiler it might pick garbage value as well
If you define an object with an initializer, it's initialized to the specified value. If you only specify values for some members, the others are initialized to zero (meaning
0
for integers (including characters),0.0
for floating-point values, andNULL
for pointers).If you define an object without an initializer, all members are implicitly initialized to zero if the object has static storage duration, i.e., if it's defined outside any function or if it's defined with the
static
keyword.An object defined inside a function without the
static
keyword has automatic storage duration. Such objects, if not explicitly initialized, start off with garbage values. (If you happen to see such objects seemingly initialized to zero, remember that zero can be just as much a garbage value as anything else.)You asked:
but the code in your question doesn't initialize the
char[]
fields. See pmg's answer, which shows some good examples, but doesn't currently mention thestatic
vs. automatic distinction.