1. Why the values of static and global variables are initialized to zero by default?
2. How can we write our own sizeof() operator?
1. Why the values of static and global variables are initialized to zero by default?
2. How can we write our own sizeof() operator?
Here's a graph of the options:
1. The values start out uninitialized.
2. The values start out initialized
.... a. The values start out at zero
.... b. The values start out at some value other than zero
Case 1 is obviously not preferred.
Case 2b is strange. If it's not zero, what value would it be? What justification would there be for that particular value?
Case 2a makes the most sense.
It involves using an array. That's probably enough of a hint.How can we write our own sizeof() operator?
Yes that is my query, why Case 1 is not preferred?
Because in the case of a global variable, there isn't even such a thing as "uninitialized." It exists as a physical object within the program image. Whereas local variables are created dynamically on the stack when a function is executed.
Why would a programmer prefer to have their global variables start out with random values, when it costs absolutely nothing to initialize them directly in the program image?
And a corollary is that you don't generally prefer that automatic variables, those with local scope, undergo run-time hits to initialize them. But those variables with program lifetime, whose initialization takes place before main, it is preferred.
With regard to sizeof, it involves knowing the size of the object to be represented, which can be calculated knowing (the composite of) the elementary components composing the object and any alignment issues.
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
Please say me how to do it! I cannot do it myself.
I'm perfectly willing to enlighten you, but if this IS a homework assignment, I think you would benefit from doing it yourself.
Some facts to consider: sizeof(char) == 1, always. And the data members of arrays are always packed as closely as possible. The solution is going to involve some type-casting.
look in limits.h for a start