+ 4
What is the logic behind this ??
2 Réponses
+ 5
The double quotes indicate that "Geeks" is a char array. A char array with five letters has a size of 6 because of the terminating null character '\0' that is automatically appended.
Single quotes indicate that 'Geeks' is of type char. Char is the smallest integer type with a size of 1 byte. 1 byte can store 2^8 = 256 unique values. G has an ASCII value of 71, e is 101, k is 107 and s is 115. So you're initializing an integer with the value
G - 256^4*71 +
e - 256^3*101 +
e - 256^2*101 +
k - 256^1*107 +
s - 256^0*115 =
304,942,678,016 +
1,694,498,816 +
6,619,136 +
27,392 +
115 =
306,643,823,475 which (is a huge number, creates an overflow and) is stored in an integer that has a size of 4 bytes.
You can actually verify this:
int n = 306643823475; // too big for an integer
cout << n << endl; // output: 1701145459
cout << 'Geeks' << endl; // output: 1701145459
+ 2
A string literal like "geeks" consists of the 5 letters (each 1 byte) plus '\0', a sign that signals the end of a string.
So the first output 6 makes sense.
The second output could just be an error (or rather undefined behaviour) because you don't write a string in single quotes... but maybe someone else knows.
Edit: Hehe, Anna knew. ^^