2009-10-22 23 views

回答

5
*s1 = *s2 

是一個表達式。 C/C++中的表達式計算爲值,在這種情況下,它返回分配給*s1的值。當'\0'被指定爲*s1時,表達式評估爲0,其清楚地爲false

+0

+1擊敗了我。 – Tom 2009-10-22 18:08:04

+0

難道它不取決於運營商的返回類型=? (是的,在這裏我們正在處理內置函數,但是有一個自定義類...) – 2009-10-22 19:13:53

+0

@Matthieu M. C/C++中的表達式總是評估一些東西。這適用於用戶定義類型或內置類型的值:struct myclass {}; int main(){myclass(); }'。我對第一句話中的「總是」並不是100%確定的,但是我對C/C++語句的理解。 – AraK 2009-10-22 19:19:00

2

是的。它必須是一個布爾表達式,可以是任何內部的表達式。

其工作原理如下:

void mystery1(char *s1, const char *s2) 
{ 
    while (*s1 != '\0') // NEW: Stop when encountering zero character, aka string end. 
     s1++; 

    // NEW: Now, s1 points to where first string ends 

    for (; *s1 = *s2; s1++, s2++) 
     // Assign currently pointed to character from s2 into s1, 
     // then move both pointers by 1 
     // Stop when the value of the expression *s1=*s2 is false. 
     // The value of an assignment operator is the value that was assigned, 
     // so it will be the value of the character that was assigned (copied from s2 to s1). 
     // Since it will become false when assigned is false, aka zero, aka end of string, 
     // this means the loop will exit after copying end of string character from s2 to s1, ending the appended string 

     ; // empty statement 
    } 
} 

這樣做是從S2的所有字符複製到S1末端,基本上追加S2到S1。

要明確,\n與此代碼無關。

+0

零不被稱爲行尾。它是字符串的結尾。 – 2009-10-22 18:12:28

+0

錯字,修正。 Thx – DVK 2009-10-22 18:12:51

+0

它不代表0個字符表示空終止符。 – JonH 2009-10-22 18:13:10

0

該代碼與'\ n'無關。賦值表達式的結果是賦值變量的新值,所以當您將'\ 0'賦值給*s1時,該表達式的結果爲'\ 0',將其視爲false。循環遍歷整個字符串被複制的點。

0

是這樣的代碼,檢查額外的括號我說...:

void mystery1(char *s1, const char *s2) 
{ 
    while (*s1 != '\0') 
    { 
    s1++; 
    } 

    for (; *s1 = *s2; s1++, s2++) 
    { 
    ; // empty statement 
    } 
} 

所以,也先檢查字符串S1末端;和s1結尾的副本s2。

+0

當作用域只包含一個表達式時,不需要作用域操作符。 – Marcin 2009-10-22 18:40:09