这段代码功能是找出数组a中的最大值和次大值,但是编写过程中出现了在for循环中写逗号表达式会导致变量x1的值无法保存。
运行测试平台linux gcc。
问题代码:
#include<stdio.h>
void max2(int *, int, int);
int main(){
int a[] = {7, 8, 3, 10, 7, 4};
max2(a, 0, 6);
}
void max2(int* a, int lo, int hi){
int x1 = 0, x2 = 0;
for(int i = lo + 1, x1 = lo; i < hi; i++){
if(*(a+x1) < *(a+i)) x1 = i;}
for(int i = lo + 1, x2 = lo; i < x1; i++){
if(*(a+x2) < *(a+i)) x2 = i;}
for(int i = x1 + 1; i < hi; i++){
if(*(a+x2) < *(a+i)) x2 = i;}
printf("x1: %d\nx2: %d", x1, x2);
}
这段代码输出是:
x1: 0
x2: 3
明显不符合预期。
第二段代码写成这样之后输出就符合预期了:
#include<stdio.h>
void max2(int *, int, int);
int main(){
int a[] = {7, 8, 3, 10, 7, 4};
max2(a, 0, 6);
}
void max2(int* a, int lo, int hi){
int x1 = 0, x2 = 0;
x1 = lo;
for(int i = lo + 1; i < hi; i++){
if(*(a+x1) < *(a+i)) x1 = i;}
x2 = lo;
for(int i = lo + 1; i < x1; i++){
if(*(a+x2) < *(a+i)) x2 = i;}
for(int i = x1 + 1; i < hi; i++){
if(*(a+x2) < *(a+i)) x2 = i;}
printf("x1: %d\nx2: %d", x1, x2);
}
输出:
x1: 3
x2: 1
所以想问一下各位为啥会出现这样的情况。