I'm new to C++, and this question will probably seem trivial to many, but please keep in mind I am just starting the C++ language.
I have assigned a variable x
to equal 20
and want to concatenate it with a string. My C++ code is below.
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main() {
int x = 20;
int y = 15;
if (x >= y) {
cout << x + " is greater than " + y;
}
}
My expected outcome would be 20 is greater than 15
, but what instead comes up is some odd é@
. I'm confused, and I couldn't find a solution on GeeksForGeeks, w3schools, or the rest of SO.
I understand that using cout << x << " is greater than " << y;
works just fine, but I'm not sure why concatenation doesn't work here. Also, why do these odd characters come out instead?
Thanks in advance.
(Also, please don't leave an answer without answering the question. I remember when starting JS I asked a question and the only answer was "don't use document.write
." While I get that, it would be far better to actually answer the question and put that as a side note.)
The reason you get some weird output is a part of C++'s history being an evolution of C. In the expression x + " is greater than " + y
the expression " is greater than "
is a const char*
literal which is a raw C-style type. It is not a C++ class type like std::string
due to backwards compatibility reasons.
Your +
signs add integers to a const char*
. This results in pointer arithmetic. Basically, " is greater than "
being a const char*
, it is a pointer to some buffer of memory whose contents are ASCII bytes for " is greater than "
. The effect of adding x
and y
to that is to move the pointer to the right 35 bytes where it will go off the end of the buffer and read uninitialized memory. That is the "odd characters" that come out. Properly speaking this is undefined behavior so anything could happen. In real systems though this will just be a buffer overflow read resulting in gibberish characters.
As others have noted, a way to fix this would be to use std::to_string
on the integers. Then, instead of int + const char* + int
you would get std::string + const char* + std::string
which is handled much better.
If this is unclear you can look up pointers, C-style strings, and buffer overflows for more info.
Edit: Technically speaking string literals are const char[]
but I have omitted this for clarity.