[CPPHTP7 NOTES] CH8. POINTERS(3)

来源:互联网 发布:部落冲突攻略软件 编辑:程序博客网 时间:2024/06/05 15:33

(Exercise 8.14) In this exercise, a piece of code is given. Readers are asked to guess what the program does. After reading the code quickly, I can say that the program is to concatenate a string at the end of another string. However, the code is quite tricky that I don't know how it exactly works. As I result, I asked for help in QQ group and Jio and Sficton provided the explanation. Thanks to them, now I understand and can share what I learn with all of you!

I have slightly modified the code for better readability:

#include <iostream>using namespace std;void mystery( char* s1, char* s2 ){while( *s1 != '\0' ) // oops, what is this simple loop for?s1++;for( ; *s1 = *s2; s1++, s2++ ) // this one is more confusing!; // nothing inside? does the loop change nothing?}int main(){char str1[] = "improve";char str2[] = "ment";mystery( str1, str2 ); // nothing is returnedcout << str1 << endl; // but str1 is change}

Okay, so can you explain to me what the program is doing? No? Let me explain it step by step.


1. The main function pass two char[] to mystery function, which has two char* as parameters. Since this is pass by reference, the value of the char[]'s element can be modified. (But the locations str1 and str2 point to do not change)


2. The mystery function start with a simple while loop. The loop increase the char pointer s1 by 1 in each iteration and ends when *s1 equals the null character. Recall that a char string ends with the null character '\0', e.g. char str[]="apple" then str[0] is 'a' and str[5] is '\0'. So s1 points to the end of the string, the null character, after the loop.


3. Then, there is a for loop. The for loop initializes nothing! It increase both s1 and s2 by 1 in each iteration and ends when *s1 = * s2 returns false. So the actual action of the for loop is done in the condition part but not the content. Wait! *s1 = *s2 as condition? What does it mean? Well, when an assignment expression is used as the condition, it returns the value of the assigned variable.So *s1 = *s2 returns false if and only if 0 is assigned to *s1. Since the null character '\0' is equivalent to 0, the loop stops after s2 is incremented to the location of a null character, in other words, the end of string 2. To conclude, this loop append each char in s2 to the end of s1 (the original '\0' of s1 is overwritten). In this example, str1 finally becomes "improvement".

0 0
原创粉丝点击