Hello, the output of this code is 'ef' but if we add up a "newline" print after this print then the output becomes 'efd'. Then why in earlier scenerio the 'd' was not getting printed ?

#include<stdio.h>

int main()
{
printf("\nab\bcd\ref");
}

3
Contributors
9
Replies
46
Views
4 Years
Discussion Span
Last Post by Rahul47

You print \n. Then you print ab\bcd on the second line. \b is the backspace leaving acd. Then you print \r which results in going to the start of the current line. Then you print ef. The lin already contained bcd so it will now contain efd with the position being on the d. If you add a printf("\n"); it would overwrite the d so the second line would contain bc then.

I'm not sure why the posted fragment prints efd for you. Maybe I'm wrong here. (Can't compile at the moment..)

Edited by Gonbe

I think you might wanna check your output, because I executed your code on codepad.com and i got following output.

I think you might wanna check your output.

As '\n' drops cursor one line down.
Then prints ab.
Then '\b' backspaces one character and prints cd. So now output is acd.
Finally '\r' returns carriage to beggining and overwrites ac with ef, so final output will be efd.

Hence output will be one line followed by efd.

Tested in linux.

@Rahul47 the website may be having some different comiling system, the web output is not correct.
plz check it on windows or linux system creating a .c file

No it's not. Using gcc I get \nefd as output when printing \nab\bcd\refd and the output is \nefg when printing \nab\bcd\refdg. The newline doesn't overwrite the 'd' which I also edited in my last post, unsure why it didn't went through.

the web output is not correct.
plz check it on windows or linux system creating a .c file


Based on what knowledge? As stated in the other thread about this it seems pretty likely compilers deal with this in different ways. Aside from it being a "puzzle" I don't see much practical use for this by the way..

plz check it on windows or linux system creating a .c file

Ummm. . . I have checked windows output with Dev C++ Compiler and Linux no need for compiler as echo statement implements whitespaces.

Edited by Rahul47: mistakes

Aside from it being a "puzzle" I don't see much practical use for this by the way..

Well you never know when you come across a problem with it's practical use, having knowledge about different things is not a waste. :-)

@Gnobe: You should check your first reply, I think you committed mistake there.

you said 'bcd' instead of 'acd'

The lin already contained bcd so it will now contain efd with the position being on the d.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.