Reason for the Output

后端 未结 6 1456
醉话见心
醉话见心 2021-01-13 12:36
#include
int main(void)
{
 int a=5;
 printf(\"%d\"+1,a);
}

Output: d. I didn\'t get how the output is coming: d ?

6条回答
  •  -上瘾入骨i
    2021-01-13 12:56

    You passed as first argument of printf "%d"+1; "%d" is actually seen as a const char * that points to a memory location where %d is stored. As with any pointer, if you increment it by one, the result will point to the following element, which, in this case, will be d.

    a is not used, but this should not be a problem since in general (I don't know if it's standard-mandated Edit: yes it is, see bottom) the stack cleanup responsibility for variadic functions is up to the caller (at least, cdecl does it that way, this however may or may not be UB, I don't know*).

    You can see it easier this way:

    #include
    int main(void)
    {
        int a=5;
        const char * str="%d";
        printf(str + 1, a);
    }
    

     

    str ---------+
                 |
                 V
              +----+----+----+
              |  % |  d | \0 |
              +----+----+----+
    
    str + 1 ----------+
                      |
                      V
              +----+----+----+
              |  % |  d | \0 |
              +----+----+----+
    

    Thus, ("%d"+1) (which is "d") is interpreted as the format string, and printf, not finding any %, will simply print it as it is. If you wanted instead to print the value of a plus 1, you should have done

    printf("%d", a+1);
    


    Edit: * ok, it's not UB, at least for the C99 standard (§7.19.6.1.2) it's ok to have unused parameters in fprintf:

    If the format is exhausted while arguments remain, the excess arguments are evaluated (as always) but are otherwise ignored.

    and printf is defined to have the same behavior at §7.19.6.3.2

    The printf function is equivalent to fprintf with the argument stdout interposed before the arguments to printf.

提交回复
热议问题