tags:

views:

138

answers:

6
#include<stdio.h>
int main(void)
{
 int a=5;
 printf("%d"+1,a);
}

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

+10  A: 

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

Ignacio Vazquez-Abrams
+17  A: 

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, cedcl 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.
Matteo Italia
+1 for nice diagram!
Daren Thomas
Thank you :) (random text to reach 15 chars)
Matteo Italia
Passing the unused value to printf is required to not be a problem by the standard. The actual implementation is, of course, allowed to vary, but I've not seen other than as you describe.
Roger Pate
@Roger Pate: found it, I'll edit the answer.
Matteo Italia
+1  A: 

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

Ruel
+1  A: 

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

Benoit
A: 

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

Sinan Ünür
A: 

"%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"

Muthu