首页 > 解决方案 > Clarification about precedence of operators

问题描述

I got this snippet from some exercises and the question: which is the output of following code:

main()
{
    char *p = "ayqm";
    printf("%c", ++*(p++));
}

My expected answer was z but the actual answer was in fact b. How is that possible?

Later edit: the snippet is taken as it is from an exercise and did not focus on the string literal or syntax issues existent in other than the printf() code zone.

标签: coperator-precedence

解决方案


Your program is having undefined behavior because it is trying to modify the string literal "ayqm". As per the standard attempting to modify a string literal results in undefined behavior because it may be stored in read-only storage.

The pointer p is pointing to string literal "ayqm". This expression

printf ("%c", ++*(p++));

end up attempting to modify the string literal that pointer p is pointing to.

An undefined behavior in a program includes it may execute incorrectly (either crashing or silently generating incorrect results), or it may fortuitously do exactly what the programmer intended.


推荐阅读