+ 26
[SOLVED] Weird Output
Can anyone explain the output of the given code ? I thought this should have done string concatenation like JS but it is giving strange output which seems like garbage data. What is happening here ? https://code.sololearn.com/c3HM1604T0OU/?ref=app
15 Answers
+ 28
Interesting.
What I think happened here is that the string literal returns a const char*, and then the integer value is added to the pointer value, resulting in garbage values being inserted into ostream, which happens to be overloaded for char pointers.
I've tested it with
std::cout << 5 + "hellotest";
which outputs "test". This agrees with my explanation. The pointer value was shifted 5 places to the right, pointing to character t. In the case of an empty string literal, the shift always goes out of bound, which explains the weird output (garbage values / whatever leftover it was in the memory space). To add to that, you can observe that
std::cout << 5 + "";
and
std::cout << 3 + "" + 2;
returns the same thing, because the pointer value was shifted to the same position.
+ 29
Nice 🤔🤔🤔
we have quizzes on that :-
std::cout<<5+"sololearn"
//outputs:- earn...
which can be explained as hasty explained but
still I can't understand y standards POSIX & gnu , C are printing out...
the more I learn C++ the more it gets weird✌️👍😎
+ 21
5
823
56
//might he wants this output
+ 21
@ Gaurav Agrawal @ Swapnil Srivastava
thanks for that idea 👍😉
https://code.sololearn.com/cjj8mgRWD57x/?ref=app
+ 20
nice output 😂
+ 20
//thats how String pattern is made 😂
#include <iostream>
using namespace std;
int main() {
cout << 5+"" <<endl;
cout << 6+"" << endl;
cout << 7+"" << endl;
cout <<8+"" <<endl;
cout <<9+"" <<endl;
return 0;
}
+ 18
I know that I cannot add string and int.
I'm just asking why is such an output coming. I thought an error should have come.
+ 18
a very interesting output 👍😉
+ 15
@Saurabh Tiwari I'm not sir. I'm a schoolboy.
I discovered it just by mistake.
+ 13
Warning: #justmonika
#include <iostream>
int main() {
int i = 0;
while(1)
std::cout << (i++)+"" << std::endl;
}
+ 7
In C++, you can’t just convert from int to string with no problem, but there are functions to do this:
stoi(string): String to int
stof(string): String to float
stod(string): String to double
to_string(T): Number to string
These won’t work in SL because of a bug with their compiler but they work anywhere else.
+ 6
my question is how u discovered it swapnil sir!!!
+ 6
didn't knew that u are a school boy and assumed that u might be elder than me..
+ 5
That is because you cannot add a string and a numeric data type
0
#include<iostream>
using namespace std;
intmyfun(const char list[], char key, intlistSize)
{
int low = 0;
int high = listSize - 1;
while (high >= low) {
int mid = (low + high) / 2;
if (key < list[mid])
high = mid - 1;
else if (key == list[mid])
return mid;
else
low = mid + 1;
}
Can anyone find asymptotic notation of worst case for this?