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; }
4 Antworten
0
Edward Finkelstein
Because you are not comparing value you are comparing reference and both character array have different reference.
+ 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.
+ 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;
}
+ 1
Ipang
Yeah of course, thanks. This was from some challenge. Personally I never use c-strings unless I really have no other choice.