Which is considered better style?
int set_int (int *source) {
*source = 5;
return 0;
}
int main(){
int x;
set_int (&x);
}
OR
int *set_int (void) {
int *temp = NULL;
temp = malloc(sizeof (int));
*temp = 5;
return temp;
}
int main (void) {
int *x = set_int ();
}
Coming for a higher level programming background I gotta say I like the second version more. Any, tips would be very helpful. Still learning C.
Neither.
Or:
Just because higher-level programming languages do a lot of allocation under the covers, does not mean that your C code will become easier to write/read/debug if you keep adding more unnecessary allocation 🙂
If you do actually need an int allocated with malloc, and to use a pointer to that int, then I’d go with the first one (but bugfixed):
Note that the function set_int is the same either way. It doesn’t care where the integer it’s setting came from, whether it’s on the stack or the heap, who owns it, whether it has existed for a long time or whether it’s brand new. So it’s flexible. If you then want to also write a function which does two things (allocates something and sets the value) then of course you can, using
set_intas a building block, perhaps like this:In the context of a real app, you can probably think of a better name than
allocate_and_set_int…