How is it that the variable used before its declaration?

I am confused about the dictCreate() function in the dictCreate() file. I am going to paste the code here:

 /* Create a new hash table * T = O(1) */ dict *dictCreate(dictType *type, void *privDataPtr) { dict *d = zmalloc(sizeof(*d)); _dictInit(d, type, privDataPtr); return d; } 

the d variable is used in zmalloc(sizeof(*d)) , but theoretically it will exist when this line is executed. So my question is, how can I use the variable d before declaring it?

+6
source share
3 answers

sizeof not a function, it is an operator. It is executed (estimated, to be precise) at compile time, so the region or lifetime you think of d is not applicable here. All you need to know is the *d type, and this is known at compile time. Enough.

+7
source

Statement

 dict *d = zmalloc(sizeof(*d)); 

equivalently

 dict *d; d = zmalloc(sizeof(*d)); 

So dict *d declares d as a pointer to a type of dict and = zmalloc(sizeof(*d)); used for initialization. dict *d = zmalloc(sizeof(*d)); declares d as dict * , and then initializes it on one line.

+1
source

Your assumption is incorrect, the object exists, starting with the = sign, which starts initialization. For example, in the initializer, you are allowed to use the address of the object that you are initializing.

Here, in addition, there is no access to the object itself, sizeof uses only this type.

+1
source

All Articles