mardi 1 mars 2022

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?

Aucun commentaire:

Enregistrer un commentaire