0

We have a statement like- printf("Hello World"); Does printf append a null character after 'd' in the given string?

1
  • 1
    No , printf does not do that in any case . Commented Feb 19, 2016 at 6:17

3 Answers 3

4

When you write

printf("xyz");

you are actually passing a string consisting of three characters and a null-terminator to printf.

printf("xyz");
// is equivalent to
static const char xyz[] = { 'x', 'y', 'z', 0 };
printf(xyz);

both printfs have the same effect: they write the characters x, y and z to the console. The null-terminator is not written.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

#include <stdio.h>

int main()
{
    char string0[] = {'a', 'b', 'c'};
    char string1[] = {'a', 'b', 'c','\0'};
    printf("%s", string0);
    puts("");
    printf("%s", string1);
    return 0;
}

If you are lucky enough, you will see something like:

abc$#r4%&^3
abc

printf() does not append a '\0' to the string. It doesn't make any change to the string to be output, because its task is to "print", rather than "modify". Instead, it is the null characters that tell printf() where is the end of the strings.

Comments

0

When a string is defined e.g. "hello world" it is null terminated by default. printf does nothing related to null terminate expect its own print processing. It only accepts char* as input. In your example "Hello World" is temp string and null terminated already before passed to printf. If the passed string is not null terminated then the behavior is undefined.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.