Reputation: 996
I've been working with some C code and I would like to know what the difference is between next codes:
double myArray[5] = {0,0,0,0,0};
and
double myArray[5];
memset(myArray,0,5*sizeof(double));
Could there be a problem for replacing the second one with the first one? If so, what kind of problems might be?
Upvotes: 2
Views: 177
Reputation: 90105
In addition to dbush's answer, although there likely wouldn't be a problem on most modern systems using memset
, the memset
version (as written) is more brittle. If someday you decided to change the size of myArray
, then one of two things would happen with the version using the braced initializer list:
myArray
, you will get a compilation error about having too many initializers.myArray
, any elements without an explicit initializer will automatically be initialized to 0.In contrast, with the memset
version:
myArray
without remembering to make a corresponding change to memset
, memset
will write beyond the bounds of the array, which is undefined behavior.myArray
without remembering to make a corresponding change to memset
, elements at the end will be uninitialized garbage.(A better way to use memset
would be to do memset(myArray, 0, sizeof myArray)
.)
Finally, IMO using memset
in the first place is more error-prone since it's quite easy to mix up the order of the arguments.
Upvotes: 1
Reputation: 224387
Using memset
this way makes assumptions regarding the representation of floating point numbers, specifically that the representation of all bits 0 corresponds to the value 0.
If your system uses IEEE754 floating point representation (as are most systems you're likely to come across) this assumption holds. However, if you find yourself running your code on some exotic system that does not, then you might not get the result you expect.
Upvotes: 4