lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Em qua., 11 de nov. de 2020 às 08:23, Ranier Vilela <ranier.vf@gmail.com> escreveu:
Em ter., 10 de nov. de 2020 às 23:07, 云风 Cloud Wu <cloudwu@gmail.com> escreveu:
Ranier Vilela <ranier.vf@gmail.com> 于2020年11月10日周二 下午9:54写道:
>
> Ok, I think that it was very clear.
> But C programmer shouldn't worry about filling memory with NULLs,

The point is as Andrew Gierth said , "modern compilers will
transform assignment loops into memset calls or inline implementations
of memset if circumstances suggest it will be both allowable and
efficient to do so" .

In my opinion, better C code should express the programmer's intention directly.
We need init the array with NULLs, memset is only a shallow
optimization that the compilers can do it well.
The cut took out of context.
I said "when".

And yet, in many cases, it is not necessary to initialize the array with NULLs, especially if it is a large array.
Good C codes are always defensive.

I usually code like this:
char * names[32000];
names[0]=NULL;

void func(names, size) {
unsigned int i;
for(i = 0; i < size; ++i) {
    if (names[i] == NULL) { /* end of array? */
        break;
    }
   // etc etc etc
}
return;

With one simple move, will reset the entire array.
Another example:

struct array {
    sizet_t size;
    size_t alloc;
    struct * mystruct[1];
} ARRAY;

ARRAY * mt;

mt->size = 0; /* reset the entire array */
void func(ARRAY * mt) {
unsigned int i;
unsigned size = mt->size; /* array length */
for(i = 0; i < size; ++i) {
   // etc etc etc
}
Again, with one simple move, will reset the entire array.

No need to reset with NULLs, the entire array.
Sorry, replace "unsigned int" with "size_t".

Ranier Vilela