Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return empty string in c

Tags:

c

string

In my function I want to return an empty string "", function looks like this:

char *myFunction(nodeType *arg){
   if (something){
      return anotherFunction(arg);
   } else {
      return EMPTYSTRING;
   }
}

(EMPTYSTRING should be replaced with correct expression to return "")

Some ways I came up with:

return ""

return '\0'

What is the right way to return an empty string?

like image 846
Misho Tek Avatar asked Oct 01 '17 17:10

Misho Tek


People also ask

How do I completely empty a string in C?

You can use c[i]= '\0' or simply c[i] = (char) 0 . The null/empty char is simply a value of zero, but can also be represented as a character with an escaped zero.

What does an empty string return?

An empty string has a Length of 0. The following example creates an empty string and displays its value and its length. String^ s = ""; Console::WriteLine("The length of '{0}' is {1}.", s, s->Length); // The example displays the following output: // The length of '' is 0. String s = ""; Console.

Can a string be null in C?

Terminology nitpick: strings can't be set to NULL; a C string is an array of characters that has a NUL character somewhere. Without a NUL character, it's just an array of characters and must not be passed to functions expecting (pointers to) strings. Pointers, however, are the only objects in C that can be NULL.

Is empty string and null same in C?

The value null represents the absence of any object, while the empty string is an object of type String with zero characters. If you try to compare the two, they are not the same.


2 Answers

It is not good idea to return "". Because, it is const char and you may try to dealloc it in where you get it from the function and this likely crashes your application.

So, I would return strdup(""), so you can free it safely.

like image 178
Adem Avatar answered Oct 03 '22 22:10

Adem


return '\0' is not correct; it is a null character.

return "";

is more correct.

And you can make a small test function to test returning an empty string, before your data structure is implemented.

like image 42
Basya Avatar answered Oct 03 '22 22:10

Basya