What does (char)0 mean in c++?

Go To StackoverFlow.com

1

What is the meaning of (char)0.

For example what does this mean?

array[1] = (char)0;
2012-04-04 02:46
by Ravindu
Assigns 0 to the array element? The cast is probably superflous - Niklas B. 2012-04-04 02:47
Your question title says C++, but your tags include C. Which is it? (The answer differs, at least theoretically, based on language. - Robᵩ 2012-04-04 02:53
c++ (sorry about thet - Ravindu 2012-04-04 02:54


5

It's a C-style cast. That is, it converts 0 (which is a literal of type int) to char (the \0 character). That cast could have been avoided entirely by simply using the '\0' literal.

2012-04-04 02:47
by Etienne de Martel
what's the purpose of doing that - Ravindu 2012-04-04 02:50
Not in C, where '\0' has type int - dan04 2012-04-04 02:50
@dan04 The question says C++ - Etienne de Martel 2012-04-04 02:51
@Ravindu Hard to say without seeing the rest of the code. My guess is that the programmer wanted to avoid a warning by assigning an int to a char, but using a cast instead of just a litteral seems overkill - Etienne de Martel 2012-04-04 02:52
while(line.at(i) != '\t') { surname[j] = line.at(i); i++; j++; } surname[j] = (char)0; i++; j = 0 - Ravindu 2012-04-04 02:55
@Ravindu Yeah, useless. Just use '\0' instead of (char)0. And if line is std::string, then use operator[] instead of at() if you're sure you'll never go out of bounds - Etienne de Martel 2012-04-04 02:57
@Etienna what happens from '\0'? - Ravindu 2012-04-04 03:02
@Ravindu '\0' is a character literal constant that is the null character (0 in ASCII) - Etienne de Martel 2012-04-04 03:04
means after i assigned '\0' to the last array position it won't print any garbage values for the rest of the array which i doesn't apply any values. right - Ravindu 2012-04-04 03:11
@Ravindu Well, it's zero, so, it's the end of a C string - Etienne de Martel 2012-04-04 03:16
@Etienna thank you very much for the hel - Ravindu 2012-04-04 03:17


2

It's 0 casted to a char, which is '\0'.

2012-04-04 02:47
by Ignacio Vazquez-Abrams
what exactly happen by it - Ravindu 2012-04-04 02:49
Generally nothing, since the typing between numbers (in the byte range) and characters is weak in C - Ignacio Vazquez-Abrams 2012-04-04 02:50


0

You are casting an int (integer) (0) to a character (char).

Casting means you are changing the type.

2012-04-04 02:48
by Attila
Ads