Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 views
in Technique[技术] by (71.8m points)

c - 这是C语言的不确定行为吗? 在clang和GCC中的结果不同(Is this a C language undefined behaviour? Different results in clang and GCC)

I'm getting different results for the same code with different compilers.

(对于使用不同编译器的相同代码,我得到了不同的结果。)

Is this a undefined behaivour?

(这是不确定的行为吗?)

#include <stdio.h>
int a;
int b=10;
int puan_ekle(int puan, int bonus){
    puan=puan+bonus;
    a=puan-5;
    bonus--;
    return bonus;
}
int main(){
    a=23;
    printf("Result1 %d 
", a);
    a=a+puan_ekle(a,b);
    printf("Result2 %d 
", a);
    a=a+puan_ekle(a,b);
    printf("Result3 %d 
", a);
}
  ask by lotusexpeditor translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The order pf evaluation of the operands of an additive operator is unspecified.

(未指定加法运算符的操作数的顺序pf评估。)

So for example in this statement

(所以在这个陈述中)

a=a+puan_ekle(a,b);

one compiler can at first evaluate the value of a and then call the function puan_ekle(a,b) that has a side effect of changing a.

(一个编译器可以首先评估a的值,然后调用具有改变a副作用的函数puan_ekle(a,b)。)

While other compiler can at first call the function and after that get the value of a after it was changed in the function.

(而其他编译器可以首先调用该函数,然后在函数中对其进行更改后获得a的值。)

So the program has undefined behavior.

(因此,该程序具有未定义的行为。)

If the function had no the side effect then the behavior would be well-defined independently of the order of evaluation of operands of the additive operator.

(如果函数没有副作用,那么行为将被良好定义,而与加法运算符的操作数的评估顺序无关。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...