Understand the low-level in the following code:

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;

19! = 109641728


but when value>19:

20! = -2102132736

or

21! = -1195114496


Why this happen?

You are overflowing a signed long. Max value is 2147483647 or 2^31
Also, refrain from using goto; statements, they're... Not exactly, preferred... Around these parts.


Use a while() {;} loop instead :)
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');
}
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!
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/
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.