In c (or maybe c++) , what's the difference between
char myarr[16]={0x00};
and
char myarr[16]; memset(myarr, '\0', sizeof(myarr));
??
edit: I ask this because in vc++ 2005 the result is the same..
edit more :
and
char myarr[16]={0x00,};
?
maybe can get more comprehensive answer and not ambiguous as some answers below refer to this kind of code,ie.
put comma just before closing curly braces. Also the result is the same in vc++ 2005.
Best Answer
The important difference is that the first default initializes the array in an element-specific manner: Pointers will receive a null pointer value, which doesn't need to be 0x00 (as in all-bits-zero), booleans will be false. If the element type is a class type that's not a so-called POD (plain old data-type), then you can only do the first one, because the second one only works for the simplest cases (where you don't have virtual functions, user defined constructors and so on). In contrast, the second way using the memset sets all elements of the array to all-bits-zero. That is not always that what you want. If your array has pointers for example, they won't be set to null-pointers necessarily.
The first will default initialize the elements of the array, except for the first one, which is set to 0 explicitly. If the array is local and on the stack (that is, not a static), the compiler internally often does a memset to clear the array out. If the array is non-local or static, the first version can be considerably more efficient. The compiler can put the initializers already, at compile time, into the generated assembler code, making it require no runtime code at all. Alternatively, the array can be laid out on a section that is automatically zero'd out (also for pointers, if they have a all-bits-zero representation) when the program starts in a fast manner (i.e page-wise).
The second does a memset explicitly over the whole array. Optimizing compilers will usually replace a memset for smaller regions with inline machine code that just loops using labels and branches.
Here is assembler-code generated for the first case. My gcc stuff isn't much optimized, so we got a real call to memset (16 bytes at the stack-top are always allocated, even if we got no locals. $n is a register number):
The gory details from the C++ Standard. The first case above will default-initialize remaining elements.
8.5
:8.5.1
: