#include <cstdio>
#include <cstdlib>
#include <iostream>
usingnamespace std;
int main()
{
char a [] = "Jim";
char b [] = "Jim";
if (a == b)
{
cout << a << " and " << b << " are equal.\n" << endl;
}
else
{
cout << a << " and " << b << " are not equal.\n" << endl;
}
return 0;
}
Jim and Jim are not equal.
Process returned 0 <0x0> execution time : 0.060 s
Press any key to continue.
you cannot compare c-like strings like that. Either use std::string class to store your string and compare them with == or use strcmp() function to compare your strings
Okay, you are telling me I can't compare strings like that, well, that I already know (it won't work), but you are not telling me why it won't work. What's going on inside of the brain of c++ that rejects this way of doing it?
The compiler allocated some memory region to contain elements of array a and another memory region to contain elements of array b. And the compiler initialized these regions with characters of string literals "Jim".
Now consider expression
a == b
In expressions names of arrays are implicitly converted to addresses of their first elements. As I noted above a and b occupy different regions of memory so their addresses are also different. In this expression you are comparing initial addresses of these memory regions. Of course they are different. So the value of the expression is equal to false.
can be either equal to true or to false. Why? Because the C++ standard says that any compiler can place two string literals with the same content either in the same memory region or in two separate different regions. It usually depends on a compiler option.
Again in this expression it is addresses of the memory regions that are compared.:)
Ah, so creating weak arrays of characters from string literals allows the characters to be modified at runtime? I didn't know this - yet another quirk of C++ with arrays and string literals.
Well, it's an array, and the elements are not constant. Arrays are ALWAYS allocated on the stack, so of course he can modify it during runtime. A string literal is usually only in the ROM of the program, not on the stack.
Well, it's an array, and the elements are not constant. Arrays are ALWAYS allocated on the stack, so of course he can modify it during runtime. A string literal is usually only in the ROM of the program, not on the stack.
I know, the part I didn't know was that the string literal was actually copied into the array on the stack. I thought the [] just degraded into a pointer in that case, but apparently it still acts as an array.