|
-
May 5th, 2011, 02:19 PM
#16
Re: Function problem
 Originally Posted by fuzzylr
I would like some advice. I would like to reduce the use of goto in this function even though it's fairly simple. What if I wanted to reuse bits and pieces of code? Can I do that or once I get into If / else or While loops do I need to move the code pieces inside the loop till it breaks out or what not. It seems kind of pointless to duplicate the code. I guess that is why the goto is so appealing in this type of instance.
Code:
int add()
{
char answer;
int a,b;
int total;
start:
std::cout<<"Enter first number: ";
std::cin>>a;
std::cout<<"Enter Second number: ";
std::cin>>b;
total = a+b;
std::cout<<"\nSum: "<< total <<"\n\n";
question:
std::cout<<"Do you wish to continue: Y/N ";
std::cin>>answer;
switch (answer)
{
case 'y': goto start;
case 'Y': goto start;
case 'n': goto end;
case 'N': goto end;
default:
std::cout<<"Invalid characters. Use Y/N or y/n.\n\n";
goto question;
}
end:
std::cout<<"Returning to menu";
sleep(3);
return 0;
}
would it be bad if I did cases like this?
Code:
case 'y' || 'Y': code sample here
My Goal is to consolidate the code down as small as possible while still being functional.
My god, this is C++ not BASIC. Remove those gotos and replace them with loops and conditionals.
C++ supports 3 types of loop, they are counted (for loop), top tested (while loop ) and bottom tested (do/while loop).
Code:
for( int i = 0; i < 10; ++i )
{
// executed 10 times
}
while( variable != value )
{
// executes while variable is not equal to value
}
do
{
// always executes once, and maybe more
} while ( variable != value );
All better choices than a goto!
Get Microsoft Visual C++ Express here or CodeBlocks here.
Get STLFilt here to radically improve error messages when using the STL.
Get these two can't live without C++ libraries, BOOST here and Loki here.
Check your code with the Comeau Compiler and FlexeLint for standards compliance and some subtle errors.
Always use [code] code tags [/code] to make code legible and preserve indentation.
Do not ask for help writing destructive software such as viruses, gamehacks, keyloggers and the suchlike.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|