A. Eaxon - 1 year ago 69
C++ Question

# Why a JS function returns different results in C++?

A riddle:

You have 3 catalogs. Each of them contains 2 catalogs. Each of those catalogs contains 1 catalog, and those are empty. How many catalogs do you have?

I wrote a JavaScript function to solve it…

``````function catalogsNumber(c)
{
n = 0;

for (a = 0; a < c; a++) {
n = (n + 1) * (a + 1);
}

return n;
}
``````

…and it returns correct results:

``````// Results in JavaScript
catalogsNumber ( 3 ) => 15
catalogsNumber ( 4 ) => 64
catalogsNumber ( 5 ) => 325
catalogsNumber ( 12 ) => 1302061344
catalogsNumber ( 13 ) => 16926797485
catalogsNumber ( 14 ) => 236975164804
``````

But when I tried the same in C++, the function returned strange results every time when
`c > 12`
:

``````int catalogsNumber(int c)
{
int i, n = 0;

for (i = 0; i < c; i++) {
n = (n + 1) * (i + 1);
}

return n;
}

// Results in С++
catalogsNumber ( 3 ) => 15              // correct
catalogsNumber ( 4 ) => 64              // correct
catalogsNumber ( 5 ) => 325             // correct
catalogsNumber ( 12 ) => 1302061344     // correct
catalogsNumber ( 13 ) => -253071699     // ¯\_(ツ)_/¯
catalogsNumber ( 14 ) => 751963524      // ¯\_(ツ)_/¯
``````

Such a riddle, very mystery. Why does it happen?

Int can store a value of: 2147483647 and you are trying to store: 16926797485

``````int catalogsNumber(int c)
{
// Change to long int instead of int or some other bigger datatype,
// the value can't be stored inside an int
short i = 0;
long int n = 0;

for (i = 0; i < c; i++) {
n = (n + 1) * (i + 1);
}

return n;
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download