Skip to content

Ask for type less often #158

@a-p-jo

Description

@a-p-jo

For instance, the following :

#define kv_push(type, v, x) do {									\
		if ((v).n == (v).m) {										\
			(v).m = (v).m? (v).m<<1 : 2;							\
			(v).a = (type*)realloc((v).a, sizeof(type) * (v).m);	\
		}															\
		(v).a[(v).n++] = (x);										\
	} while (0)

can be rewritten as :

#define kv_push(v, x) do {									\
		if ((v).n == (v).m) {										\
			(v).m = (v).m? (v).m<<1 : 2;							\
			(v).a = realloc((v).a, sizeof(*(v).a) * (v).m);	\
		}															\
		(v).a[(v).n++] = (x);										\
	} while (0)

The key difference is that asking for type simply to take sizeof(type) can be error prone (and the errors can be hard to debug) and is redundant when the size of the type can be determined by taking sizeof() of a variable known to be of the same type in the structure passed to us. It is also sweeter syntax, as an aside.

Also, why do we use trust malloc()/realloc() to always succeed ?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions