Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the expression 'ab' == "ab" true in C++

My question sounds probably quite stupid, but I have to answer it while preparing myself to my bachelor exam.

So, what do you think about such an expression 'ab' == "ab" in C++? Is this not true or simply not legal and compiling error? I have googled a little and get to know that 'ab' is in type int and "ab" of course not...

I have to regard not what compilator says but what says formal description of language..

like image 441
Nastasja Avatar asked Nov 28 '12 20:11

Nastasja


3 Answers

It definitely generates a warning, but by default, gcc compiles it. It should normally be false.

That being said, it should be theoretically possible, of course depending on the platform you're running this on, to have the compile-time constant "ab" at a memory location whose address is equal in numerical value to the numerical value of 'ab', case in which the expression would be true (although the comparison is of course meaningless).

like image 120
Vlad Avatar answered Nov 06 '22 21:11

Vlad


In both C and C++ expression 'ab' == "ab" is invalid. It has no meaning. Neither language allows comparing arbitrary integral values with pointer values. For this reason, the matter of it being "true" or not does not even arise. In order to turn it into a compilable expression you have to explicitly cast the operands to comparable types.

The only loophole here is that the value of multi-char character constant is implementation-defined. If in some implementation the value of 'ab' happens to be zero, it can serve as a null-pointer constant. In that case 'ab' == "ab" becomes equivalent to 0 == "ab" and NULL == "ab". This is guaranteed to be false.

like image 4
AnT Avatar answered Nov 06 '22 23:11

AnT


It is going to give you a warning, but it will build. What it will do is compare the multibyte integer 'ab' with the address of the string literal "ab".

Bottom line, the result of the comparison won't reflect the choice of letters being the same or not.

like image 1
imreal Avatar answered Nov 06 '22 21:11

imreal