Dee A
Dee A

Reputation: 3

printf returns 6 instead of 0 when assigning a null string

Why does printf function return 6 instead of 0 when assigning NULL as string to it, although its printing nothing?

int main(void)
{
    int x;
    x = printf("%s", NULL);
    printf ("\n%d", x);
}

output is:

(null)
6

Upvotes: 0

Views: 101

Answers (1)

KamilCuk
KamilCuk

Reputation: 141768

why does printf function return 6 instead of 0 when assigning NULL as string to it

Because it printed 6 chars. "(null)" is 6 chars.

although its printing nothing?

It is printing "(null)". That's 6 chars.

Note that passing NULL as an argument to %s format specifier is invalid in the first place and causes undefined behavior. Some implementations, like the one you are using, are printing "(null)" instead of crashing.

Upvotes: 5

Related Questions