Comparison with string literal results in unspecified behaviour?

In C++ == only implemented internally for primitive types and array is not a primitive type, so comparing char[100] and string literal will only compare them as 2 char* or better to say as 2 pointers and since this 2 pointers can’t be equal then items[n] == "ae" can never be true, instead of this you should either use std::string to hold string as:

std::string items[100];
// initialize items
if( items[n] == "ae" ) ...

or you should use strcmp to compare strings, but remeber strcmp return 0 for equal strings, so your code will be as:

char items[100][100];
// initialize items
if( strcmp(items[n], "ae") == 0 ) ...

And one extra note is if (items == 0) is useless, since items allocated on stack and not in the heap!

Leave a Comment