哪个被认为是更好的风格?
int set_int (int *source) {
*source = 5;
return 0;
}
int main(){
int x;
set_int (&x);
}
Run Code Online (Sandbox Code Playgroud)
要么
int *set_int (void) {
int *temp = NULL;
temp = malloc(sizeof (int));
*temp = 5;
return temp;
}
int main (void) {
int *x = set_int ();
}
Run Code Online (Sandbox Code Playgroud)
为了获得更高级别的编程背景,我得说我更喜欢第二个版本.任何提示都会非常有帮助.还在学习C.
都不是.
// "best" style for a function which sets an integer taken by pointer
void set_int(int *p) { *p = 5; }
int i;
set_int(&i);
Run Code Online (Sandbox Code Playgroud)
要么:
// then again, minimise indirection
int an_interesting_int() { return 5; /* well, in real life more work */ }
int i = an_interesting_int();
Run Code Online (Sandbox Code Playgroud)
正因为高级编程语言在幕后做了很多的分配,也不能意味着你的代码将变得更容易读/写/调试,如果你继续添加更多不必要的分配:-)
如果你确实需要一个用malloc分配的int,并使用一个指向那个int的指针,那么我会选择第一个(但是有bug):
void set_int(int *p) { *p = 5; }
int *x = malloc(sizeof(*x));
if (x == 0) { do something about the error }
set_int(x);
Run Code Online (Sandbox Code Playgroud)
请注意,函数set_int 在任何一种方式都是相同的.它不关心它设置的整数来自何处,无论是堆栈还是堆,谁拥有它,它是否已存在很长时间或是否是全新的.所以它很灵活.如果你还想编写一个执行两项操作的函数(分配一些东西并设置值),那么你当然可以使用它set_int作为构建块,也许是这样的:
int *allocate_and_set_int() {
int *x = malloc(sizeof(*x));
if (x != 0) set_int(x);
return x;
}
Run Code Online (Sandbox Code Playgroud)
在真正的应用程序的上下文中,你可能会想到一个比allocate_and_set_int... 更好的名字
| 归档时间: |
|
| 查看次数: |
546 次 |
| 最近记录: |