操作数的求值顺序

考虑下面的程序。

null

C++

// C++ implementation
#include <bits/stdc++.h>
using namespace std;
int x = 0;
int f1()
{
x = 5;
return x;
}
int f2()
{
x = 10;
return x;
}
int main()
{
int p = f1() + f2();
cout << ( "%d " , x);
getchar ();
return 0;
}


C

#include <stdio.h>
int x = 0;
int f1()
{
x = 5;
return x;
}
int f2()
{
x = 10;
return x;
}
int main()
{
int p = f1() + f2();
printf ( "%d " , x);
getchar ();
return 0;
}


JAVA

class GFG {
static int x = 0 ;
static int f1()
{
x = 5 ;
return x;
}
static int f2()
{
x = 10 ;
return x;
}
public static void main(String[] args)
{
int p = f1() + f2();
System.out.printf( "%d " , x);
}
}
// This code is contributed by Rajput-Ji


Python3

# Python3 implementation of the above approach
class A():
x = 0 ;
def f1():
A.x = 5 ;
return A.x;
def f2():
A.x = 10 ;
return A.x;
# Driver Code
p = A.f1() + A.f2();
print (A.x);
# This code is contributed by mits


C#

// C# implementation of the above approach
using System;
class GFG {
static int x = 0;
static int f1()
{
x = 5;
return x;
}
static int f2()
{
x = 10;
return x;
}
// Driver code
public static void Main(String[] args)
{
int p = f1() + f2();
Console.WriteLine( "{0} " , x);
}
}
// This code has been contributed
// by 29AjayKumar


PHP

<?php
// PHP implementation of the above approach
$x = 0;
function f1()
{
global $x ;
$x = 5;
return $x ;
}
function f2()
{
global $x ;
$x = 10;
return $x ;
}
// Driver Code
$p = f1() + f2();
print ( $x );
// This code is contributed by mits
?>


Javascript

<script>
x = 0;
function f1()
{
x = 5;
return x;
}
function f2()
{
x = 10;
return x;
}
var p = f1() + f2();
document.write(x);
// This code is contributed by Amit Katiyar
</script>


输出:

10

上述程序的输出是“5”还是“10”? 输出未定义,因为f1()+f2()的计算顺序不是标准要求的。编译器可以自由地首先调用f1()或f2()。只有当表达式中出现等优先级运算符时,关联性才会出现。例如,f1()+f2()+f3()将被视为(f1()+f2())+f3()。但在第一对中,标准并没有定义首先计算哪个函数(操作数)。 感谢文基提出的解决方案。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享