Reputation: 133
In C or C++ I know that there is something called
undefined behaviour
In expression evaluation when some of the the expressions have side-effects. let's say I want to calculate the following:
c = 10
f() + g() + c
but at some point g makes c = 5.(c is a glob variable)
What would be the behavior in python? Would it be undefined as C?
Upvotes: 9
Views: 2560
Reputation: 214740
C code such as this:
#include <stdio.h>
int c;
int f (void)
{
return 1;
}
int g (void)
{
return ++c;
}
int main()
{
c = 3;
printf("%d", f() + g() + c);
return 0;
}
does not invoke undefined behavior. It does however invoke unspecified behavior. These are different, formal terms: Undefined, unspecified and implementation-defined behavior
Note first that f() + g() + c
is grouped as (f() + g()) + c
but that tells you nothing about the order in which the terms themselves are actually evaluated.
The result of this code can either be 1 + (3+1) + 3 = 8
or 1 + (3+1) + 4 = 9
, depending on if the operand g()
is evaluated before or after the operand c
. The order of evaluation of operands of the +
operator is unspecified, so we can't know which operand that gets evaluated first, nor should we write code that relies on a certain order.
The code will only ever give either of the two mentioned results, it will not do anything completely crazy, like crashing or giving garbage results, which code containing undefined behavior could do. An example of undefined behavior would be c++ + c++
.
The difference between the examples is where the side effects take place. See Undefined behavior and sequence points
Upvotes: 5
Reputation: 4814
If c
is a global
variable, and g()
is making the same c
to be the value of 5
, meaning that this is unspecified behaviour
.
Note, Python interpreters evaluate expressions from left to right, meaning that the c
would be 5 when it's added to f() + g()
.
Upvotes: 1
Reputation: 30936
From 6.15 of python documentation
Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.
In the following lines, expressions will be evaluated in the arithmetic order of their suffixes:
expr1, expr2, expr3, expr4
(expr1, expr2, expr3, expr4)
{expr1: expr2, expr3: expr4}
expr1 + expr2 * (expr3 - expr4) <----- This is of importance to us.
expr1(expr2, expr3, *expr4, **expr5)
expr3, expr4 = expr1, expr2
So here the functions will be called in order from left to right. So any of the changes you will see will be due to the functions called from left to right.
And yes in python function calls are expressions.
Upvotes: 10