我有一个main
方法看起来像这样。
struct list *l = array_list();
if (l == NULL) {
return EXIT_FAILURE;
}
srand(time(NULL));
int size = 4;
for (int i = 0; i < size; i++) {
int *d = malloc(sizeof(int));
*d = rand();
list_insert_last(l, d);
printf("inserted: %d\n", *d);
}
printf("size: %zu\n", list_size(l));
for (int i = 0; i < size; i++) {
int *d = list_delete_first(l);
printf("deleted: %d\n", *d);
free(d);
}
printf("size: %zu\n", list_size(l));
array_list_free(l);
return EXIT_SUCCESS;
我的问题是,即使我已经标记premature-optimization
了int *d
变量。
一旦退出循环并重用它会更好地声明变量吗?
struct list *l = array_list();
if (l == NULL) {
return EXIT_FAILURE;
}
srand(time(NULL));
int size = 4;
int *d; // declare once
for (int i = 0; i < size; i++) {
d = malloc(sizeof(int)); // reuse it
*d = rand();
list_insert_last(l, d);
printf("inserted: %d\n", *d);
}
printf("size: %zu\n", list_size(l));
for (int i = 0; i < size; i++) {
d = list_delete_first(l); // reuse it
printf("deleted: %d\n", *d);
free(d);
}
printf("size: %zu\n", list_size(l));
array_list_free(l);
return EXIT_SUCCESS;