回报值问题? [英] Return value problem?
问题描述
在这里我很惊讶输出它总是给1可以任何人PLZ解释这里有什么回报以及它是如何以及它返回的是什么?
我尝试过:
#include< stdio.h>
int main()
{
int a = 5,b;
b =有趣(a);
printf(%d,b);
}
int fun(int a)
{
返回 - && a ++;
}
不要这样做。
问题在于 - 并且语言没有定义后增量和减量操作:它们可以在执行行之前,行执行之后或行执行期间完成 - 它们可以按编译器的任何顺序完成作家认为合适 - 所以他们可以从左到右,从右到左,或RPN堆栈顺序,或者......
所以你可以不知道何时执行帖子增量:它可能是:
x = a;
a + = 1;
a - = 1;
返回x&& x;或
x = a;
a + = 1;
y = a;
a - = 1;
返回x&& y;或其他一些组合。
在这种情况下,它可能是第二种选择 - 但它不一定是,并且玩是一个坏主意这些结果可能会有所不同,具体取决于您使用的编译器,甚至调试版本和发布版本之间的优化!
保持修改前和修改后的操作简单:使它们复杂化会使代码变得困难阅读,难以理解和不可靠!
建议:当你使用递增/递减时,不要多次使用变量,它是一个灰色区域,因为编译器可以自由重写你的代码,结果是不可预测的。
在你的情况下,你只关心a
不等于零。在C中,对于任何变量,0为假
和非零为真
。
所以你的代码意味着true和true
并导致1
因为它意味着true
here i am surprised with the output it is always giving 1 can anyone plz explain what return is doing here and how and what it is returning ?
What I have tried:
#include<stdio.h> int main() { int a=5,b; b=fun(a); printf("%d",b); } int fun(int a) { return a--&&a++; }
Don't do that.
The problem is that exactly when pre- and post- increment and decrement operations are done is not defined by the language: they can be done before the line is executed, after the line is executed, or during the line execution - and they can be done in any order that the compiler writer finds appropriate - so they could be done left-to-right, or right-to-left, or RPN stack order, or ...
So you can't tell when the post increments are performed: it could be:
x = a; a += 1; a -= 1; return x && x;Or
x = a; a += 1; y = a; a -= 1; return x && y;Or some other combination.
In this case, it's probably the second option - but it doesn't have to be and it's a bad idea to "play" with these things as the result can differ depending on the compiler you use, or even the optimisations between a debug build and a release build!
Keep pre- and post- modification operations simple: complicating them makes code hard to read, hard to understand, and unreliable!
Advice: Never use a variable more than once when you play with increment/decrement, it is a gray zone as the compiler is free to rewrite your code, the result is unpredictable.
In your case, you only care thata
is different of zero. In C, for any variable,0 is false
andnon zero is true
.
so your code meanstrue and true
and result in1
because it meantrue
.
这篇关于回报值问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!