-1

So I've been trying to use strcat like this lately and I've always got an error:

strcat(string, 'a');

And then I realised that I have to use something which contains '\0' as the second parameter, in order to have a const char* .

Well, I was just playing around in VS, and using strcat like this:

strcat(string, "a");

rendered no error.

This is very strange to me, because some days ago I've learnt that I need to create an auxiliary char, like this:

aux[0] = 'a';
aux[1] = '\0';
strcat(string, aux);

if I wanted to add only a character to a string.

Now I'm a bit lost to be honest.

Can anybody explain what's the difference between ' and " when using chars?

Thanks.

  • 4
    Single quotes for single characters. Double quotes for null.terminated strings. And in C a single character is usually implicitly converted to `int` values, and null terminated strings are really arrays of characters (including the terminator). A literal string (using double-quotes, like e.g. `"a"`) is an array of non-modifiable (read-only) characters. – Some programmer dude May 14 '20 at 16:53
  • @Someprogrammerdude thanks for your answer. – Octavian Niculescu May 14 '20 at 17:02

2 Answers2

3

String literals are implicitly null-terminated. These are equivalent declarations:

const char a[] = "a";
const char a[] = { 'a', '\0' };
Carl Norum
  • 219,201
  • 40
  • 422
  • 469
3

' (single quote) is for creating a single character which is almost the same thing as an integer.

On the other hand " (double quote) is used for creating a constant char pointer which means a memory block that is terminated with a null and contains characters in it.

You can put as many characters as you want in double quotes, but ' will always contain a single character.

Also you cannot compare double quoted strings for equality because, in the end of the day, what it creates is a pointer which is the starting point of your string which is a 32 or 64 bit integer on most machines. On the other hand comparing chars (single quoted) is fine because they are values themselves rather then being pointers to addresses.

Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
nikoss
  • 3,254
  • 2
  • 26
  • 40