Quote Originally Posted by fuzzylr View Post
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!