0

I have two similar codes in C++ and Python.
C++ Code

#include <iostream>
using namespace std;

int i = 0;

int fcn()
{
    i = 1;
    return 1;
}

int main()
{
    i = 0;
    i = i + fcn();
    cout << i << endl;
}

Output: 2

The output is 2, and I think it is because of the precedence of function call is higher than addition.

Python code

def fcn():
    global x
    x = 1
    return 1

x = 0
x = x + fcn()
print(x)

Output: 1

The output is 1, which I am not sure how it works.
This page says that function call also has higher priority than addition in Python.
So, why does these two codes have different ouputs, is there any misunderstanding?

chengi666
  • 1
  • 1
  • 4
    You never even call `fcn` in your C++ code...? – Random Davis Apr 06 '22 at 16:13
  • Your C++ code has [**undefined behavior**](https://stackoverflow.com/questions/949433/why-are-these-constructs-using-pre-and-post-increment-undefined-behavior). – Jason Apr 06 '22 at 16:14
  • See: https://stackoverflow.com/q/4176328/315052 – jxh Apr 06 '22 at 16:14
  • 1
    @jxh That's C, and C++ has a delightful tradition of changing fundamental things once in a while. – Passer By Apr 06 '22 at 16:15
  • Where do you call `fcn()` in the c++ code? – 2pichar Apr 06 '22 at 16:15
  • It doesn't matter whether OP is calling `fcn` or not. The code has UB. – Jason Apr 06 '22 at 16:16
  • Sorry, I have edited my C++ code. – chengi666 Apr 06 '22 at 16:21
  • @AnoopRana The program has unspecified behavior, but not undefined behavior. It will output either `1` or `2`. (Oh just noticed that the code was edited! You were correct before) – user17732522 Apr 06 '22 at 16:23
  • Note that operator precedence isn't actually the same as the order of evaluation of operands. You are correct that function call has higher precedence than addition. `x + fcn()` is interpreted as `(x) + (fcn())`, not as `(x + fcn)()`. But given that the expression is interpreted as `(x) + (fcn())`, that still doesn't tell you whether `x` or `fcn()` is evaluated first. – Nathan Pierson Apr 06 '22 at 16:24
  • @user17732522 Ok, lol – Jason Apr 06 '22 at 16:27
  • Btw. the question is not entirely clear on whether you are asking about the C++ code or the Python code (you should try to avoid asking two things in one). The linked duplicate explains the problem in case of C++, but as far as I am aware (might be wrong though) in Python there is a defined order of evaluation. So the explanation in the duplicate is not applicable to Python. – user17732522 Apr 06 '22 at 16:31
  • @AnoopRana Like https://chat.stackoverflow.com/rooms/116940/c-questions-and-answers or https://chat.stackoverflow.com/rooms/10/loungec? Though I have never been there. – user17732522 Apr 06 '22 at 16:34

0 Answers0