Unexpected behavior of printf()

I executed following code in ubuntu with gcc compiler.

As a=0, the second printf() prints some garbage value.

What kind of behavior is it by printf()?

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int a = 0;

    printf("\nThe Value of %ns : %d\n", &a, a);
    printf("\n%d\n", a);

    printf("\n\n");

    return 0;
}

Upvotes: 1

Views: 116

Answers (3)

As a=0, the second printf() prints some garbage value.

You can't believe that statement until you verify it!

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int a = 0;
    printf("\nThe Value of %ns : %d\n", &a, a);
    assert(a == 0);
    printf("\n%d\n", a);
    printf("\n\n");
}

Any time you want to say "I'm sure that (some invariant) is true at place x", use assert to state that fact and let it be checked at runtime.

Output:

output.s: ./example.c:8: main: Assertion `a == 0' failed.

Upvotes: 0

hayoola
hayoola

Reputation: 131

The output of the first printf is 0
Because the second argument of printf passes a by the value and it gets printed afterwards.

The output of the second printf is 14 Because at this time the value of a was replaced by the number of characters that was printed before %n by the first printf

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409136

If you read e.g. this printf reference you will see that the %n format specifier will:

returns the number of characters written so far by this call to the function.

So it will overwrite the contents of a with the number of characters it has written so far, which should be 14 if I count correctly.

Upvotes: 3

Related Questions