Understand the low-level in the following code:
Jul 12, 2010 at 5:21pm UTC
Hi,
I'm Learning C++
and I make this exercise:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
// factorial calculator
#include <iostream>
using namespace std;
long number;
char r;
long factorial (long a)
{
if (a > 1)
return (a * factorial (a-1));
else
return (1);
}
void want(){
loop:cout << "Please type a number" ;
cin >> number;
cout << number << "! = " << factorial (number) << endl;
cout << "Another value? [y/n]" << endl;
cin >> r;
if (r == 'y' ) goto loop;
}
int main ()
{
want();
return 0;
}
when I put a value of up to 19,
the code operates normally;
but when value>19:
or
Why this happen?
Jul 12, 2010 at 5:39pm UTC
You are overflowing a signed long. Max value is 2147483647 or 2^31
Jul 12, 2010 at 10:29pm UTC
Also, refrain from using goto ;
statements, they're... Not exactly, preferred... Around these parts.
Use a while () {;}
loop instead :)
Jul 12, 2010 at 11:04pm UTC
1 2 3 4 5 6 7 8 9
void want(){
do {
cout << "Please type a number" ;
cin >> number;
cout << number << "! = " << factorial (number) << endl;
cout << "Another value? [y/n]" << endl;
cin >> r;
} while (r == 'y' );
}
Jul 13, 2010 at 11:41pm UTC
Yes,
The while do solution is more elegant... :D
Also, refrain from using goto; statements, they're... Not exactly, preferred... Around these parts.
In this code, I believe that there is no performance differences between
'while'/'do' and 'goto' (?)
But in a large code (that I still have not learned how to do),
this can make a difference to the compiler and performance?
And in which situations is preferred use goto? :S
Thanks!
Jul 13, 2010 at 11:58pm UTC
pdgui wrote:And in which situations is preferred use goto? :S
Use goto only in case you want to end up like this ->
http://xkcd.com/292/ :P
This might help solving the overflow issues ->
http://gmplib.org/
Jul 14, 2010 at 6:40pm UTC
But in a large code (that I still have not learned how to do),
this can make a difference to the compiler and performance?
Yes. Avoid
goto when a superior solution exists, such as a loop. That will compile to cleaner, faster code. And it will be more maintainable and easier to read.
Topic archived. No new replies allowed.