Coming from a PHP background, I’m used to writing small functions that return a string (or the response from another function) like so:
function get_something(){
return "foo";
}
However, I’m new to C and am trying to figure how to do some really fundamental things like this.
Can people review the following similar functions and tell me how they differ and which one is the best/cleanest to use?
char *get_foo(){
char *bar;
bar = "bar";
return bar;
}
char *get_foo(){
char *bar = "bar";
return bar;
}
char *get_foo(){
char *bar = NULL;
bar = "bar";
return bar;
}
char *get_foo(){
return "bar";
}
Is there any difference between these functions or is this a style issue?
One other thing. If I have two functions and one calls the other, is this alright to do?
char *get_foo(){
return "bar";
}
char *get_taz(){
return get_foo();
}
UPDATE: How would these functions need to change if get_foo() did not return a const char*? What if get_foo() calls another function that has a char* of different lengths?
The four are equivalent, especially the first three ones – the compiler is likely to compile them to exactly the same code. So I’d go for the last one, for being smaller.
Having said that – you’re returning a const char*, not a char*, so this particular code could break everything, depending on how you use it (if it compiles at all, which you can force anyway). The thing is, you’re returing a pointer to a string that isn’t dynamically allocated, but part of the executable image. So modifying it could be dangerous.
As a more general rule, never return a pointer to stuff allocated on the stack (ie not created using new or malloc) because as soon as the function ends, the scope of that variable also ends, gets destroyed, so you get a pointer to invalid (freed) memory.