Reason for the Output

后端 未结 6 1454
醉话见心
醉话见心 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条回答
  • 2021-01-13 12:41

    You should do printf("%d", a+1). "%d" + 1 is a pointer to "d" inside an array of char ({'%','d','\0'}).

    0 讨论(0)
  • 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<stdio.h>
    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.
    0 讨论(0)
  • 2021-01-13 12:56

    Suppose you had:

    char x[] = "%d";
    

    What do you expect

    printf(x + 1, a);
    

    to print?

    Hint: t.c:5: warning: too many arguments for format

    0 讨论(0)
  • 2021-01-13 13:00

    "%d" is String constant, it will be stored in the char[] in the memory. During runtime, "%d" returns the starting location of the char[]. Increasing character array pointer by one, will point to the next character. Hence "d" alone is passed to the printf function. so the output is "d"

    0 讨论(0)
  • 2021-01-13 13:03

    String literals are pointers. Advancing the pointer to "%d" by 1 results in "d". The argument is discarded.

    0 讨论(0)
  • 2021-01-13 13:05

    Because of +1. If you want to increment a do: printf("%d", a + 1); instead.

    0 讨论(0)
提交回复
热议问题