简体   繁体   中英

What is the difference between char ch and char ch = 0?

I'm reading through chapter 10 of Stroustrup's PPP and the example he uses here when reading files:

http://www.c-jump.com/bcc/c155c/c155Stxtbook2nd/Chapter10/chapter_10_11_2_cpp.htm

When he's reading the temperature, I noticed that he uses char ch1; and char ch2;

However, when he's reading the month, I saw that he does char ch = 0;

I was wondering, what is the purpose of initializing char ch = 0; when he didn't do that in the previous function? Does it make any difference?

The char corresponding to 0x00 or \\0 generally indicates the end of a string. This is the character implied when you hear things like "null-terminated strings".

When scanning a string with functions like strlen this is what tells the function it reached the end.

This being said, looking at you link I don't see a particular reason to initialize it to 0 in the month detection and not in the other functions. In every case it looks like ch is provided with values from the stream... Of course it is a good thing to init variables, but I'd dare say it is not always necessary.

No reason. This snippet is not a good example of coding style. Arguments can be made both way: From one hand, it's a good practice to initialize variables even if you are going to re-initialize them after, and from another, why spend (even de-minimus) resources doing something which will never be used (albeit compiler is likely to detect that and skip initialization anyways).

But mixing both approaches in the same file, unless it is done exactly for the purpose of showcasing two possibilities, is just confusing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM