Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does it happened that a variable used before it's declared?

I am confused about a function dictCreate() in file dict.c of redis implementation. 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;
}

variable d is used in zmalloc(sizeof(*d)), but theoretically it will exist when this line was executed. So my question is how it is possible to use variable d before it is declared?

like image 871
ssj Avatar asked Aug 05 '15 15:08

ssj


2 Answers

sizeof is not a function, it is an operator. It is executed (evaluated, to be exact) at compile time, so the scope or lifetime you're thinking about d, does not apply here. All it needs to know is the type of *d and that is known at compile time. Sufficient.

like image 129
Sourav Ghosh Avatar answered Sep 18 '22 17:09

Sourav Ghosh


The statement

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

is equivalent to

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

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

like image 37
haccks Avatar answered Sep 19 '22 17:09

haccks