5

I have the following python code:

a, b = 1, 1
for i in range(0, 100):
    print a
    a, b = b, a + b

It generates this: 1 1 2 3 5 8 etc

I wrote the same in c:

#include <stdio.h>
long long unsigned int a = 1, b = 1;
void main(){
    for(int i = 0; i < 100; i++){
        printf("%llu \n", a);
        a = b, b = a + b;
    }
}

It generates this: 1 1 2 4 8 16 32 etc

Why does the c program generate powers of 2 when it is using the exact same operations?

BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
Programah
  • 179
  • 1
  • 10
  • 7
    The comma operator does something different in C than in Python. – EOF Jun 06 '17 at 15:47
  • 2
    Also If `long long unsigned` is 64 bits, overflow occurs at 93th(0 origin) in C. [DEMO](http://ideone.com/0dtkQI) – BLUEPIXY Jun 06 '17 at 15:56

3 Answers3

10
a, b = b, a + b

in python packs the values b and a + b into a tuple, then unpacks it back into a and b.

C does not supports that feature, but rather use the comma to separate between assignments, so a = b, b = a + b get translated as

a = b;
b = a + b;

where b gets doubled every time because the assignment is not simultaneous.

To fix that you'd have to assign each variable separately:

b = a + b;
a = b - a; // a + b - a = b
Uriel
  • 15,579
  • 6
  • 25
  • 46
3

Because , has different meanings in C and python. In python:

a, b = b, a + b

means modify a and b (simultaneously) with respective values b and a+b.

While in C:

 a = b, b = a + b;

means do a=b and then after b=a+b.

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
0

You misunderstand comma operator.

#include <stdio.h>
#include <inttypes.h>
#include <stdint.h>

int main(void) {
    uintmax_t a = 1, b = 1;
    for (int i = 0; i < 100; i++) {
        printf("%" PRIuMAX "\n", a);
        b = a + b;
        a = b - a;
    }
}
Stargateur
  • 24,473
  • 8
  • 65
  • 91