简体   繁体   English

char ch 和 char ch = 0 有什么区别?

[英]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:我正在阅读 Stroustrup 的 PPP 的第 10 章以及他在此处阅读文件时使用的示例:

http://www.c-jump.com/bcc/c155c/c155Stxtbook2nd/Chapter10/chapter_10_11_2_cpp.htm 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;当他读取温度时,我注意到他使用了char ch1; and char ch2;char ch2;

However, when he's reading the month, I saw that he does char ch = 0;然而,当他读这个月的时候,我看到他确实char ch = 0;

I was wondering, what is the purpose of initializing char ch = 0;我想知道,初始化char ch = 0;的目的是什么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. 0x00\\0对应的字符一般表示字符串的结束。 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.当使用strlen函数扫描字符串时,这会告诉函数它到达了结尾。

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.话虽如此,看着你的链接,我没有看到在月份检测中将其初始化为 0 而不是在其他函数中的特殊原因。 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.在每种情况下,看起来ch都提供了来自流的值......当然,初始化变量是一件好事,但我敢说这并不总是必要的。

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.但是在同一个文件中混合这两种方法,除非它完全是为了展示两种可能性的目的,否则只会令人困惑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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