-
goto again...
I know you guys hate goto statements, but would you consider this a good use of a goto statment:
Code:
#include <iostream>
using namespace std;
int search(long id_nums[], int size, long value);
int main()
{
long id_nums[] = {5658845, 8080152, 1005231,
4520125, 4562555, 6545231,
7895122, 5552012, 3852085,
8777541, 5050552, 7576651,
8451277, 7825877, 7881200,
1302850, 1250255, 4581002,};
long number;
int result;
cout << "Enter a number" << endl;
RESTART: cin >> number;
result = search(id_nums, 18, number);
if (result == -1)
{
cout << "Invalid number. Enter a valid number" << endl;
goto RESTART;
}
else
cout << "Your number is valid" << endl;
return 0;
}
int search(long id_nums[], int size, long value)
{
int i = 0;
int position = -1;
int found = 0;
while (i < size && !found)
{
if (id_nums[i++] == value)
{
found = 1;
position = i;
}
}
return position;
}
-
nope. Thats how microsoft think goto should be used in their code samples. The correct tool for what you are trying to do is either a while loop or a do/while loop. You dont need a goto to do that just slightly better structure.
-
do while
the part after
int result;
could be written like this:
do{
cin >> number;
result=search(id_nums,18,number);
if(result==-1)
cout << "Invalid number ..." << endl;
else
cout << "Your number is valid" << endl;
}while(result==-1);
For your program it doesn't matter whether you use goto or a loop. But if you write a program that would normally contain dozens of loops, and use goto instead, you will waste much time on searching all your labels.
Code with to many gotos is also known to cause endless loops easier. (Though, your computer doesn't know anything else than goto. Every 'while', 'for', 'do', and even every function call is a 'goto' [jump] to your computer)
-
Code:
while ((search(id_nums, 18, (cin >> number)) == -1
cout << "Invalid number. Enter a valid number" << endl;
do
cout << "Your number is valid" << endl;
return 0;
I'm not sure if I did that right...the part with the cin >> number; is a bit questionable, but it's something like that.
Edit: Somebody beat me, and their code will work for sure :) Use that
-
i sometimes use goto, but only in rare cases. gotos are mostly annoying when theyre used like 5 billion times and they start to spider web all over the place