The difference between the null termination of char (\ 0) and `^ @`

My codes look like this:

#include <iostream> using std::cout; using std::endl; int main(int argc, char *argv[]) { cout << (int)('\0') << endl; cout << (char)(0) << endl; return 0; } 

I expected to see in the terminal like this:

 $ test-program 0 $ 

However, what I saw was like this:

 $ test-program 0 ^@ $ 

What scares me is that '\0' can be converted to 0 . And 0 can also be included in \0 . I expected to see a null char value followed by endl , but the result would be something weird, like ^@ .

Does anyone have any ideas about this?

+4
source share
4 answers

^@ is how your terminal emulator displays '\0' .

+12
source

^@ is a generic representation of the null character. Similarly, ^A used to denote a character with an ordinal value of 1, ^G for a character with an ordinal value of 7 (call) and ^M for a character with an ordinal value of 13 (carriage return).

 cout << (char)0 

Just prints a character representation, not an integer representation

+7
source

If you look at the output of your terminal, you do not know if your program is running that does not behave as expected, or maybe just your terminal emulator.

On UNIXoid systems, use ./myProgram | hexdump -C ./myProgram | hexdump -C to see hex output. This way, you will make sure that your program does what you expect from it, so that a terminal that does not behave as expected:

 00000000 30 0a 00 0a |0...| 00000004 

If you see the same result as me, you are actually printing zero '0' , new line '\n' , null '\0' , new line '\n' . Thus, in this case, your program behaves as you expected.

You might want to try various terminal emulators or settings.

+1
source

If you drop 0 to char , it does not generate '0' , but '\0' - remember that casting from integral type to char creates a char with this ASCII code, Thus, basically, the second line outputs a null character (ASCII 0 )

If you want to output the '0' char, you would need to do something like (char) 48 , because 48 is the ASCII value for character 0.

0
source

All Articles