0
Illegal C++ expression accepted by C++ Code Playground
Surprised by this lesson :" 55+15 // legal C++ expression //Both operands of the + operator are integers 55 + "John" // illegal // The + operator is not defined for integer and string" yet last time the C++ Code Playground seemed to accept mixted integer and string in Conditionnal & Loops the if statment exercices : int x = 5; int y = 3; if (x > y) { // here you can mix strings & integer , I ve checked it cout << "hi there"; }
3 Respostas
+ 2
So, what is the illegal thing?
55 + "John" is perfectly legal. Even if it's not a good idea.
"John" is not actually a string, it's a char array.
A char array is basically the same as a pointer to the beginning of the array.
If you do 1 + "John" for example, you increment that pointer by 1.
So now the beginning would be at index 1 and the result would be: "ohn", if you printed it.
If you do 55 +"John" you increment the pointer by 55.
But now it points past the allocated array and you are in the realm of undefined behaviour.
But still legal C++.
0
Hello Dennis , thanks for your fast reply .
Please read carefully what I wrote.
Have a good day !
0
I did read it, could you at least give us a program that shouldn't compile but does in the lesson?