How to return empty char * ?
Hi:
Here is my code: Code:
char * func1(){ I then try: Code:
char * func1(){ |
Depending on how you're using the return value, you likely either want to return:
"\0" or NULL |
First you need to make yourself clear why you get this warning. It's appearing because you return a constant string literal while the function should return a (non const) char pointer.
I can think of two ways to fix this, one in an ugly way (but leaving the function signature intact), the other the much better way - assuming you want a valid c string as returned data. dirty (static data as returned data): Code:
char * func1() better (const correctness, valid string literal) Code:
const char * func1() |
so anything like "", gcc treats it as constant?
Another question, if I do "", does gcc treat it as string or char * ? I know in vc++, it treats "" as char *. |
Yes, GCC will treat it as 'const char *'. MSVC has some settings to treat string literals as constant too IIRC (and store them in read-only memory). Are you sure 'char *' is the default setting there ? Would be a bit surprising, but MSVC has always been a sort of black box to me concerning some of its settings.
|
what are you trying to do?
what you are returning is a constant string, i.e. compiled in. the fact that you specified it "" means it's there at compilation, so is, of course, constant |
I guess MSVC treat "" as const char *. I said char * just to say MSVC doesn't treat "" as std::string
|
Quote:
Code:
char *func1() Code:
{ |
I agree - both are bad, but I at least made a mention of it not being preferable, while you gave it as a solution to the OP. Apart from that, your code will still spawn this warning mentioned in the first post ...
And "dangerous things" ??? Oh, please ... *facepalm* |
Quote:
Quote:
If you plan to return a sting literal then the signature of your function should reflect that the return value is a const. If you are returning a string that can be modified but you want to be able to return an empty string return 0, the null pointer, and then test that the return value points to a valid address before doing anything with the value. |
so what is the final answer if I really need to return char * instead of const char * ?
|
Quote:
|
Quote:
Or is it that you want to be able to modify the char * ? |
Quote:
Quote:
Code:
[10:39:29][aconole@weston:~] With a static member: Code:
[11:08:00][aconole@weston:~] Relevant sections are 6.2.4, 6.2.5, and 6.2.6 of C99 |
Quote:
Quote:
|
All times are GMT -5. The time now is 06:15 PM. |