Return String from a Function!!

Hi,

I often see that people use code like this even in some open source(openLDAP)
char* func()
{
return "Some String";
}

Is it safe to write code like this?
Yes. (though the function should return constr char*)
"string literals" are not local variables, they're built into the exe and "hello world" just returns an address of some static array. I think..
Note that
1
2
3
4
char* func(){
   char str[] = "some string";
   return str;
}
would not be safe.
Last edited on
1
2
3
4
char* func()
{
return "Some String";
}


Not that this has anything to do with your question, but.....

Why is the return type "char"? If you return an array, be it character or whatever else, an array is essentially a pointer to first element and so shouldnt the return type be void?
And for arguments sake lets say it would be a char, even so, what is the purpose of the asterisk (*) ? Unless im jumbling my c and c++ rules...
an array is essentially a pointer to first element

Not quite. An array is a memory block. We refer to it by using a pointer to the first element, and its name, when used without a subscript, converts to a pointer to the first element.

and so shouldnt the return type be void?

If it's an array of chars, the first element is a char, so a pointer to the first element is of type char*.

what is the purpose of the asterisk (*) ? Unless im jumbling my c and c++ rules...

This notation works exactly the same in C and C++:

1
2
3
int a = 2;  // type of a is int
int* p = &a  // type of p is int*, or pointer to int
*p = 4  // now we're dereferencing p, which gets us a, and changing the value of a 
filipe wrote:

If it's an array of chars, the first element is a char, so a pointer to the first element is of type char*.


You are correct. I got confused because I saw functions whereby an array was used in them but wasnt returned by them and hence a void was returned.
Hey guys,. I have not get the responsible answer of my question. Please tell me is 'hamsterman' is correct?
TIA
I am.
I have doubts about the exact implementation of them, but that's nothing you should be concerned with.
Hi,

If you write something like
 
return "Some String";

in your program, the compiler stores that string in the data segment of the program(exe). So when you say "return "Some String"", it means you are returning a pointer which points to a data segment, not a stack. So it is absolutely safe. Data segment values can't be changed. Thats why these are reffered as "const char*" than "char*".

Compiler does this for the optimization purpose. If you say something like
 
string str = "Some String";

in somewhere else in the same program, compiler reuses the already initialized "Some String"
rather than allocate a new memory.
Topic archived. No new replies allowed.