Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why and how does the following outputs involving the carriage return show up?

Tags:

c

output

gcc

#include <stdio.h>

void main()
{
    printf("ab");
    printf("\bsi");
    printf("\rha");
}

this code gives the output of "ha" on GCC 4.8 compiler

#include <stdio.h>

void main()
{
    printf("ab");
    printf("\bsi");
    printf("\rha");
    printf("\n");
}

this code gives the output of "hai" on GCC 4.8 compiler

now the question is why does the output change from "ha" to "hai" just on adding the statement printf("\n"); at the end which (according to me) should not affect the code due to the preceding lines.

like image 395
aroonav Avatar asked Mar 21 '23 09:03

aroonav


2 Answers

When your program ends, the shell writes the prompt starting at whatever position the cursor was last on. So in the first case, after \rha, the cursor is sitting on the i. The shell will overwrite the i with whatever the first character of your prompt is.

In the second case, you output a \n at the end which moves the cursor to the next line, where the shell writes its prompt.

like image 92
Greg Hewgill Avatar answered Apr 12 '23 14:04

Greg Hewgill


First of all you need to understand the white space characters:

  1. \n :: It moves the cursor to the next line.
  2. \b :: It moves the cursor one character back to the left of Console. Just simply backspaces one character.
  3. \r :: Carrage Returns.It moves cursor to extreme right of the same line.

So result of printf statments are:: 1. Prints "ab" , cursor sitting at end of line. 2. Prints "asi" after moving the cursor back one space (\b), cursor sitting at the end of a line. 3. Prints "hai", cursor sitting after ha, just below i.

So, OUTPUT :: hai

In first case you are not able to see 'i' because of the cursor whereas in second due to newline character you are able to see it

like image 43
Vikas Sangle Avatar answered Apr 12 '23 15:04

Vikas Sangle