[CPPHTP7 NOTES] CH8. POINTERS(3)

(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 returned
	cout << 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值