简体   繁体   English

C ++:像这样的for循环如何工作(使用指针)?

[英]C++: How does a for loop like this one work (using pointers)?

I just came across this for loop in a reference book but I'm not really sure what's going on in the comparison since it's just a lone pointer. 我刚刚在参考书中看到了这个循环,但是我不确定比较中发生了什么,因为它只是一个单独的指针。

char input[300], *p, *q[300], **r = q;
cin.getline(input, 300);
for (p = input; *p; p++)

How would it work? 它会如何工作?

input is a null-terminated string. input是以null结尾的字符串。 cin.getline will place a 0 after the last character of the read string or at input[299] if the line exceeds 299 characters. 如果行超过299个字符,则cin.getline将在读取字符串的最后一个字符后面或在input[299]处放置一个0

The char value gets implicitely converted to a boolean. char值被隐含地转换为布尔值。 It becomes true if it's not zero and consequently false if it's zero. 如果它不为零则变为真,如果它为零则变为假。 Thus the loop condition is equivalent to *p != 0 . 因此,循环条件等于*p != 0

Therefor the loop will iterate over the array until it comes across a zero, the end of the string. 因此,循环将遍历数组,直到它遇到零,即字符串的结尾。

The second expression in a for statement is evaluated for "truthiness". for语句中的第二个表达式被评估为“真实性”。 A character is true if is not equal to 0. The for loop could be changed to the following equivalent one: 如果不等于0,则字符为true.for循环可以更改为以下等效的:

for (p = input; *p != 0; p++)

Since strings are null-terminated, this is how one iterates through the characters in a string, and stop at the end. 由于字符串以空值终止,因此这是一个遍历字符串中字符的方式,并在结尾处停止。

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

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