 Đumić Branislav - 3 years ago 426
Pascal Question

# Why functions do not give integer overflow

I have wrote functions in C++ and Pascal that give me n-th Fibbonacci number. As expected for large n-values(n>92,because even f(93) > 2^63+1) I was getting incorrect results.

But when I compared them for same n I would get same result in both languages.

This was opposed to my idea that I would get some random number.

I am wondering why I am getting same results and why I didn't get integer overflow in the first place.

Could somebody explain this to me?

Code:

``````#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

long long fibo(int n){
long long a1,a2,pom;
int i=1;
a1 = 0; a2 = 1;
while(i<=n){
pom = a2;
a2 = a1 + a2;
a1 =  pom;
i++;
}
return a1;
}

int main(){
int n;
cin >> n;
cout << "Function: "<< setprecision(50) << fibo(n) << endl;
}
``````

``````Program AddNums(output);
function fibo(n:integer):int64;
var
a1,a2,pom:int64;
i:integer;
begin
a1:=0;a2:=1;i:=1;
while(i<=n)do
begin
pom:= a2;
a2:= a1 + a2;
a1:= pom;
inc(i);
end;
fibo:=a1;
end;
var
n:integer;
begin
writeln(fibo(n));
end.
`````` dasblinkenlight
In your case Pascal and C++ programs use the same underlying hardware with the same representation of `int64` and `long long`, and they instruct that hardware to perform the same sequence of mathematical operations on numbers that start off the same. Hence, they do arrive at the same number, representing the end result of this sequence of operations.