2012-02-04 84 views
9
void swap(int &first, int &second){ 
    int temp = first; 
    first = second; 
    second = temp; 
} 

//////輸出參數用C

int a=3,b=2; 
swap(a,b); 

在上述例子中,C編譯器抱怨 「空隙交換(INT &第一,整數&秒)」 語法有錯誤。像以前一樣「/ {(」失蹤「&」

我不明白爲什麼不支持C此功能

+1

或者你可以第二^ = *先使用XOR交換:)'*先^ = *第二,*, *首先^ = *秒;' – 2012-02-04 21:04:46

+0

你介意使用#define嗎?如果是,則交換(a,b)b^= a; a^= b; b^= a; – QuentinUK 2012-02-04 21:08:15

+10

XOR掉期等屬於IOCCC,並非以實際的代碼或作爲初學者的建議。通過引用傳遞的 – 2012-02-04 21:16:42

回答

12

C不支持按引用傳遞。所以,你需要使用指針做你想要達到的:

void swap(int *first, int *second){ 
    int temp = *first; 
    *first = *second; 
    *second = temp; 
} 


int a=3,b=2; 
swap(&a,&b); 

我做建議是:但我會添加它的完整性。

如果參數沒有副作用,則可以使用宏。

#define swap(a,b){ \ 
    int _temp = (a); \ 
    (a) = _b;  \ 
    (b) = _temp;  \ 
} 
21

C不支持通過引用傳遞;γ T帽子是C++的特色。您必須改用指針。

void swap(int *first, int *second){ 
    int temp = *first; 
    *first = *second; 
    *second = temp; 
} 

int a=3,b=2; 
swap(&a,&b); 
0

的整數交換,你可以使用這個方法沒有一個局部變量:

int swap(int* a, int* b) 
{ 
    *a -= *b; 
    *b += *a; 
    *a = *b - *a; 
} 
+0

爲避免'warning:控制到達非void函數的末尾'應該是'void swap(int * a,int * b)'(從不傷害檢查if(* a!= * b)交換之前......) – 2017-05-30 05:06:08