0

Output of C++ code

Why does it output 0 and not 1? #include <iostream> using namespace std; int main() { char a[]="tashkent"; char b[9]="tashkent"; cout << a << endl << b << endl; cout << (int)(a==b); //why 0 and not 1? return 0; }

16th May 2021, 7:58 PM
Edward Finkelstein
Edward Finkelstein - avatar
4 odpowiedzi
0
Edward Finkelstein Because you are not comparing value you are comparing reference and both character array have different reference.
16th May 2021, 8:03 PM
A͢J
A͢J - avatar
+ 3
Use strcmp() from <cstring> if you want to compare content of C-string for equality/inequality. http://www.cplusplus.com/reference/cstring/strcmp/ Comparing *a and *b only compares the first character of C-string <a> and <b>, the rest are not compared so the result is not valid. You are coding in C++, I'd recommend to use std::string instead of C-string.
16th May 2021, 11:26 PM
Ipang
+ 1
Ah ok, you are right. So I apply the dereferncing operator and then I get 1 😀 #include <iostream> using namespace std; int main() { char a[]="tashkent"; char b[9]="tashkent"; cout << a << endl << b << endl; cout << (int)(*a==*b); return 0; }
16th May 2021, 8:49 PM
Edward Finkelstein
Edward Finkelstein - avatar
+ 1
Ipang Yeah of course, thanks. This was from some challenge. Personally I never use c-strings unless I really have no other choice.
16th May 2021, 11:47 PM
Edward Finkelstein
Edward Finkelstein - avatar