This problem is found during the full arrangement of exercise numbers:
#include <stdio.h>#include <stdlib.h>//#define swap(a,b) {a=a+b;b=a-b;a=a-b;}#define swap(a,b) {tmp=a;a=b;b=tmp;}int g_count=1;int g_n=0;void p(int *a,int size);void print_result(int *a);int main(int argc, char *argv[]){ int array[]={1,2}; g_n=sizeof(array)/sizeof(int); p(array,g_n); system("PAUSE"); return 0;}void print_result(int *a){ int i=0; printf("count %d:",g_count++); //printf("g_n=%d",g_n); for(i=0;i<g_n;i++) { printf(" %d",a[i]); } printf("\n"); return; }void p(int *a,int size){ if(size==1) { print_result(a); } else { int i,tmp=0; for(i=0;i<size;i++) { //printf("before1:a%d=%d,a%d=%d\n",i,a[i],size-1,a[size-1]); swap(a[i],a[size-1]); //printf("before2:a%d=%d,a%d=%d\n",i,a[i],size-1,a[size-1]); p(a,size-1); swap(a[i],a[size-1]); //printf("after:a%d=%d,a%d=%d\n",i,a[i],size-1,a[size-1]); } } return;}
The code above implements a full array of numbers, but uses define swap (a, B) {a = a + B; B = a-B; a = a-B ;} and # define swap (a, B) {tmp = a; a = B; B = tmp;} get different results. Is it a problem with the compiler? The compiler is dev c ++. The former results are and. The result of the latter is 2, 1, and 1, 0.
Conclusion: After debugging, it is found that when the input parameter is the same, when the input parameter of swap is (a [1], a [1]), when define swap (, b) {a = a + B; B = a-B; a = a-B;} assume that the value of a [1] is 2, it may be considered that when step a = a + B is executed, a = 4, B = 2. However, after debugging, it is found that the input parameter is the same variable. Therefore, when a = 4, the value of B is also changed to 4, resulting in an unsuccessful exchange.
Therefore, it is better to use the second method to ensure security when array swapping is involved. Because it may appear when an array is switched, the input parameter is the same array value.
This article from the "Practical Experience" blog, please be sure to keep this source http://zhangjiabin.blog.51cto.com/2325830/1288273