-3

I have these two pieces of code:

int main(void)
{
    printf("\nab");
    printf("\bsi");
    printf("\rha");
    return 0;
}

For the first one the output is hai. However if I write it this way instead:

int main(void)
{
    printf("\nab");
    printf("\bsi");
    printf("\rsha");
}

The output that results is just sha. What's going on here? (Also I'm using gcc)

Rivasa
  • 6,510
  • 3
  • 35
  • 64

2 Answers2

1

1)

 printf("\nab");

it displays ab

printf("\bsi");

\bdelete the last character (\b = backspace). Then you append  si

it displays asi

printf("\rha");

\r return to the beginning of the line (\r = carriage return). Then you print ha . hence you erase the first 2 characters of asi

Hence, it displays hai

2)

Same explanation for the first 2 steps.

On the third step, you return to the beginning of the line with \r and print 3 characters, erasing the 3 characters that were previsouly present.

Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148
0

short explanation:

\n = moves to next line
\b = backspace - deletes 1 char
\r = moves cursor to 1st column of the line

so you get

ab
asi //for \bsi
hai // for \rha
Rohan
  • 52,392
  • 12
  • 90
  • 87