Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ask for type less often #158

Open
a-p-jo opened this issue Nov 17, 2021 · 0 comments
Open

Ask for type less often #158

a-p-jo opened this issue Nov 17, 2021 · 0 comments

Comments

@a-p-jo
Copy link

a-p-jo commented Nov 17, 2021

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 ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant