0
A = 0
B = 1

A, B = B, A + B 

running 5 times:

the values of B in Python will be 1, 1, 2, 3, 5. the values of B in C will be 1, 1, 1, 1, 1.

Would anyone explain this to me?

#include <stdio.h>

#define TRUE (1 == 1);
#define FALSE (1 == 0);

int fibonacci(int sequencia);

int main() {
    fibonacci(5);
    return FALSE;
}

int fibonacci(int sequencia) {
    static int antigo = 0;
    static int novo = 1;
    static int copia = 0;

    if (sequencia == 0) {
        return TRUE;
    }

    else {
        printf("%i\n", novo);
    }
    antigo, novo = novo, antigo + novo;
    fibonacci(sequencia - 1);
}
antigo = 0
novo = 1

def fibonacci(sequencia):
    global antigo, novo
    if sequencia != 0:
        print novo

    else:
        return True

    antigo, novo = novo, antigo + novo
    fibonacci(sequencia - 1)

if __name__ == "__main__":
    fibonacci(5)
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 3
    `a, b = b, a` in python and C mean _very, very different_ things. – cs95 Dec 21 '17 at 14:06
  • https://stackoverflow.com/questions/275128/parallel-assignment-in-c – Oliver Charlesworth Dec 21 '17 at 14:07
  • 1
    In general, you shouldn't expect different languages to have the same semantics even where they have identical syntax. – jonrsharpe Dec 21 '17 at 14:08
  • `antigo, novo = novo, antigo + novo;` in C does not do what you think it does. Here's what happens: 1: evaluate `antigo` and discard the result. 2: assign `novo` to `novo`. 3: evaluate `antigo+novo` and return it (but since you're not assigning the value it is still discarded). – Zinki Dec 21 '17 at 14:10
  • 2
    A bit strange to close this with a dup for C++, in my opinion. It's not obvious that they are the same in this respect (either). – unwind Dec 21 '17 at 14:23
  • @unwind Agree, I followed the link and found that it's not that difficult (now and in C++11 with `std::pair`). But these things are not available in C. (And, I must smile remembering all these comments "C and C++ are two separate lanuages...") – Scheff's Cat Dec 21 '17 at 17:47
  • C and C++ do not support multiple assignment the way Python does. In C and C++, the statement `A, B = B, A + B` is parsed as `(A), (B = B), (A + B)` and evaluated as "evaluate `A` and discard the result, then assign `B` to `B`, then evaluate `A + B` and discard the result." To do what you want in C, you'd have to use two separate assignment statements - `A = B; B = A + B;` – John Bode Dec 21 '17 at 17:58
  • John Bode and Zinki Your answers were enlightening, thank you. – William PY Dec 27 '17 at 16:34

0 Answers0