A secret C++ question ( 5 ) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

A secret C++ question ( 5 )

What is the output of this code? cout<< sizeof("Solo"); cout<< strlen("Learn"); My answer is 45 but the right answer is 55 😭

6th Mar 2018, 6:54 PM
Eros boulay
Eros boulay - avatar
6 Answers
+ 16
because sizeof count '\0' or null terminated character which is automatically added on the end of every string
6th Mar 2018, 7:12 PM
Vukan
Vukan - avatar
+ 2
Thanks,I am so foolish...
6th Mar 2018, 7:18 PM
Eros boulay
Eros boulay - avatar
+ 2
I also would've said 45 to be honest. I don't know for sure, but I guess a string directly used in sizeof (I mean without variable) contains a terminator ('\0'), while strings (datatype string) doesn't need this, because it is limited by the allocated memory for the variable. string str = "solo"; cout << sizeof(str); //-> 4 bytes allocated => output 4 cout << sizeof("solo"); //-> 5 bytes, because the program needs to know when the string ends. so it's actually "solo\0" It's just a guess. I would also like to read an actual explanation for this. edit: thanks vukan ^^
6th Mar 2018, 7:21 PM
Alex
Alex - avatar
+ 1
Yeah vukan is right
6th Mar 2018, 7:14 PM
Eike Rabetian
Eike Rabetian  - avatar
+ 1
No actually you’re not. That’s an error. Sizeof shouldn’t do that.
6th Mar 2018, 7:21 PM
Eike Rabetian
Eike Rabetian  - avatar
+ 1
solo\0 5 strlen just count the characters
6th Mar 2018, 8:07 PM
Arun