Undefined Behavior in Python

In C or C ++, I know there is something called

undefined behavior

In evaluating an expression, when some of the expressions have side effects. let's say I want to calculate the following:

c = 10
f() + g() + c

but at some point g does c = 5. (c is the glob variable)

What will be the behavior in python? Will it be undefined as C ?

+4
source share
3 answers

Out of 6.15 documentation

Python evaluates expressions from left to right. Note that when evaluating an assignment, the right side is evaluated in front of the left side.

In the following lines, expressions will be calculated in 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

, . , , , .

.

+5

C :

#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;
}

undefined. . : Undefined,

, f() + g() + c (f() + g()) + c, , .

1 + (3+1) + 3 = 8, 1 + (3+1) + 4 = 9, , g() c. + , , , , .

, , , , , undefined. undefined c++ + c++.

, . . Undefined

+3

If it cis a variable global, it g()does the same cvalue 5, which means unspecified behaviour.

Note. Python interpreters evaluate expressions from left to right, which means there cwill be 5 if it is added to f() + g().

0
source

Source: https://habr.com/ru/post/1694287/


All Articles