【发布时间】:2018-05-09 18:34:17
【问题描述】:
我试图将这段代码转换为只使用 goto 的代码,但是当我尝试在在线 IDE 上运行它时,我不断收到时间限制错误,而当我尝试在我的控制台上运行它时却没有'甚至没有反应或打印错误。
这里是原始代码:
void sort (int skip, int ∗A, int length) {
for (int n = length ; n > 1 ; n−−) {
int i = 0 ;
while (true) {
if (skip == 0 && i < n−1) {
if (A[i] > A[i +1]) {
A[i] = A[i] ^ A[i+1];
A[i +1] = A[i +1] ^ A[i] ;
A[i] = A[i] ^ A[i+1] ;
}
}else
break ;
i++;
}
}
}
这是转换后的代码:
#include <stdio.h>
void sort(int skip,int *A,int length){
int n=length;
int i,temp,temp2;
Lcond:
if(n<=1) goto Lend;
Lbody:
i=0;
Lcond_:
if(skip!=0) goto Lelse;
temp=n-1;
if(i>=temp) goto Lelse;
Lbody_:
temp2=i+1;
if(A[i]>A[temp2]) goto Lbody__;
i++;
goto Lcond_;
Lbody__:
A[i]=A[i]^A[temp2];
A[temp2]=A[temp2]^A[i];
A[i]=A[i]^A[temp2];
i++;
goto Lcond_;
Lelse:
goto Lcond;
Lend:
return;
}
int main(){
int skip=0;
int A[5]={3,5,1,4,2};
int length=5;
sort(skip,A,length);
for (int i=0;i<5;i++){
printf("%d\t",A[i]);
}
}
【问题讨论】:
-
我试图将这段代码转换为只使用 gotos 的代码 - 为什么???
-
另外,你不应该永远使用异或交换 - 如果编译器不智能,它不知道将异或交换替换为使用中间变量的交换.
-
@ChristianGibbons 下摆?
-
@ChristianGibbons 我认为你对 XOR 交换有误解。en.wikipedia.org/wiki/XOR_swap_algorithm
-
但是,如果尝试将相同的 object 与自身交换,而不是相同的值,则异或交换将失败。使用数组时可能会发生这种情况...
标签: c error-handling goto