Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it undefined behavior to compare a character array char u[10] with a string literal "abc"

I came across this question on SO, and this answer to the question. The code is as follows:

int main()
{

    char u[10];
    cout<<"Enter shape name ";
    cin>>u;
    if(u=="tri") //IS THIS UNDEFINED BEHAVIOR because the two decayed pointers both point to unrelated objects?
    {
        cout<<"everything is fine";
    }
    else
    {
        cout<<"Not fine";
    }
    return 0;
}

I have read in the mentioned answer that, both u and "tri" decay to pointers to their first element. My question is that, now is comparing these two decayed pointers undefined behavior because these pointers point to unrelated objects? Or the program is fine/valid(no UB) and because the pointers have different values, the else branch will be executed?

like image 283
Anoop Rana Avatar asked Dec 01 '25 03:12

Anoop Rana


1 Answers

Standard says:

[expr.eq]

The == (equal to) and the != (not equal to) operators group left-to-right. The lvalue-to-rvalue ([conv.lval]), array-to-pointer ([conv.array]), and function-to-pointer ([conv.func]) standard conversions are performed on the operands...

Hence, we are comparing pointers to the respective arrays.

If at least one of the operands is a pointer, ... Comparing pointers is defined as follows:

  • If one pointer represents the address of a complete object, and another pointer represents the address one past the last element of a different complete object,72 the result of the comparison is unspecified. [does not apply since neither pointer is past last element]
  • Otherwise, if the pointers are both null, both point to the same function, or both represent the same address, they compare equal. [does not apply since neither is null, neither point to functions, nor represent same address]
  • Otherwise, the pointers compare unequal. [applies]

The behaviour is defined and else branch will be unconditionally executed.

Unconditionally unconditional if-statements imply that there is probably a bug; most likely the author was trying to compare the content of the arrays, which the operator does not do.


"warning: comparison with string literal results in unspecified behavior"

I believe that this warning message is slightly misleading. Comparison with two string literals would be unspecified:

if ("tri" == "tri")

It's unspecified whether this conditional is true or false.

like image 139
eerorika Avatar answered Dec 02 '25 17:12

eerorika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!