What's the differences between ' ' and " "?

Hello,

What's the difference between ' ' and " " in the below example?

Thanks

1
2
3
4
5
6
7
8
9
10
11
  #include <iostream>
using namespace std;

int main()
{
    cout<<"TEST"<<" "<<"1";
    cout<<endl;
     cout<<"TEST"<<' '<<"2";
    return 0;
}
Hi Shervan360:

Single quotes are used for single characters and double quotes for string values.
Try this:

1
2
3
4
5
6
7
8
#include <iostream>

int main() {
    std::cout << "Test" << ' ';
    std::cout << "Test" << '  ';

    return 0;
}


While the first line prints as expected, the second line will add garbage at the end due to having the extra (unexpected) space. Change that to

std::cout << "Test" << " ";

and the garbage goes away.

Single quotes, in C++, are for single char entries.
Last edited on
The double quotes are a shorthand for C-strings, which are null-terminated char arrays.
1
2
3
" "
// is equivalent to
{ ' ', 0 }


1
2
3
"Hi S"
// is equivalent to
{ 'H', 'i', ' ', 'S', 0 }


Note that '\n' is a single (byte) char (newline character) even though in code we represent it with '\' and 'n'. Some coding systems have multibyte characters.
Topic archived. No new replies allowed.