Questions about '\b' and unary minus

closed account (j13ApfjN)
I don't really understand the meaning of unary minues operator and backspace. As my teacher mentioned that '-' is used for making the variable to be 0, and I did not observe it when testing. Also, for example:

cout<<"hi\bhello<<endl;

would output hihello
I want to know what \b do in the code.
unary minus is just like math in a textbook etc:

int x = 5;

int y = -x; //unary minus. y is now -5

its the same as, or shorthand for (conceptually, not internally)
y = x*-1;

backspace is the same as deleting the previous character using the <--- backspace char on the keyboard. It serves no purpose most of the time.
In your example, you should get hhello as the i is deleted. The only use I can think of for it (in code) is to backup and overwrite the same value for an up-to-date display of something. And it has limited usefulness there.



Last edited on
closed account (j13ApfjN)
Thank you for your explanation in the unary minus.

I tried
cout<<"hi\bhello"<<endl;

again in Eclipse and another online C++ platform.
And I get the result of "hihello"
Last edited on
> I want to know what \b do in the code.

\b is an escape sequence; an escape sequence is used to denote a special character in (character and string) literals.
http://en.cppreference.com/w/cpp/language/escape

For example:
while sizeof( "hihello" ) == 8; seven characters plus the null-terminating character,
[/tt]sizeof( "hi\bhello" ) == 9[/tt]; eight characters plus the null-terminating character.
The character at position 2 is '\b'; a single character (the value of which depends on the encoding used by the implementation).

Among all the escape sequences, the only ones which have specified behaviour when used in text-mode input or output is the new-line character \n and the tab character \t. What happens when any other special character like \b is sent as output to a text stream is entirely up to the implementation.

In particular:
Data read in from a text stream is guaranteed to compare equal to the data that were earlier written out to that stream only if all of the following is true:

- the data consist only of printing characters and the control characters \t and \n
- no \n is immediately preceded by a space character
- the last character is \n
http://en.cppreference.com/w/cpp/io/c
I got hhello, which is what I would have expected it to do. But as noted, this is not ensured and varies across tools. There are others like that also, printing control+g does not beep the speaker on all systems anymore either :)

Topic archived. No new replies allowed.