0

Basically my professor coded it another way but mine works too. I just wanted to ask is there any hidden problems in my code that I don't understand? If it's basically the same (which I'm assuming it is), I'll just do it my way.

MY CODE

int current=0, next =1, temp;
  for(int i=0;i<number;i++){
    temp = current;
    current = next;
    next +=temp;
  }
  return current;
}

PROFESSOR CODE

  int current=0, next =1, temp;
  for(int i=0;i<number;++i){
    temp = next+current;
    current = next;
    next =temp;
  }
  return current;
}
Evg
  • 25,259
  • 5
  • 41
  • 83
Furqan_25
  • 29
  • 6
  • If the code behaves the same, then just pick the one that is more readable. The compiler will generate the same assembly for both anyway. – cigien Jun 10 '20 at 19:38
  • The difference with i++ vs. ++i in behaviour does not matter for that code and the speed should be the same (a decent compiler will create the same assembly). Same applies to the application of the plus operation. My personal code would equal your code, because I think, it is more "clear". – Rennnyyy Jun 10 '20 at 19:40
  • 1
    Both are correct –  Jun 10 '20 at 19:41

2 Answers2

4

In general, the compiler will do a great job of generating optimal assembly, so I would suggest writing your code in the most readable way possible.

Here's one way of writing it that should be quite readable:

int current = 0, next = 1;

for(int i = 0; i < number; ++i )
  current = std::exchange(next, current + next);

return current;

Once you understand how std::exchange works, this should be much clearer. e.g. there's no need for a temp variable at all.

cigien
  • 57,834
  • 11
  • 73
  • 112
0

Both implementations are functionally identical. Just use whichever you find more readable.

lancegerday
  • 752
  • 1
  • 8
  • 24