-1

This program's purpose is basically to get a character from a user and repeat it. There were a few things we had to do other than that in the program but that was the gist of it.

#include <iostream>

using namespace std;

int main(){
// Variable Declaration
int repeat;
char character;

// Prompt User for Repeat & Character
cout << "Character: ";
cin >> character;
cout << "Repeat: ";
cin >> repeat;

// Loop: Check if Repeat is Negative
while (repeat < 0) {
    cout << "Repeat value cannot be negative." << endl;
    cout << "Repeat: ";
    cin >> repeat;
}

// Printing Characters According to Repeat Value
if (repeat == 0) {
    cout << endl;
    return 0;
} else {
    for (int count = 0; count < repeat - 1; ++count) {
        cout << character << " ";
    }
    cout << character;
}

// Newline after For loop
cout << endl;

// Inform Operating System (Successful)
return 0;

}

Basically I used an exit(0); in an if statement to exit out of the program like my professor wanted. He exclaimed Program execution: 7/7. All my test cases executed correctly. Good!

Source code: 2.5/3 Uninitialized: repeat, character

You have called exit to escape early. Do not do this. (Do not escape a loop early with any construct. You are using it to patch some sloppy code.)

Should I use a return rather than using exit? Why is this considered sloppy code? What are some other alternatives I could use?

I used return 0; rather than using exit(0);

12
  • 2
    Hi tanner, welcome to SO! Please avoid using screenshots of code, as people willing to help have to spend a lot of time to copy out the code. It would be great if you could add the code in a code block, rather than in a screenshot. Perhaps also add what your code is trying to accomplish? Commented Apr 2, 2024 at 23:45
  • 3
    Don't post your code as an image, copy/paste the text into your question. Commented Apr 2, 2024 at 23:46
  • 2
    Please do not upload images of code/data/errors.. Unless you write your code with a graphics editor like Paint.net, it's text, and can be copied and pasted directly into your post and formatted as code for readability. Please edit your post to correct it. Also, you'll find your experiences at SO will be much better if you take the time to complete the tour and read the help center pages to learn how the site works before you begin posting. Commented Apr 2, 2024 at 23:53
  • 3
    Do not escape a loop early with any construct. I disagree with this in the general sense. The advice applies most of the time, but I've seen folks write hideously overcomplicated code that's far harder to reason about than a loop with an exit in the middle to avoid an exit in the middle, totally defeating the point of the guideline. What you want is readable code, and if exit in the middle results in more readable code, go with the exit in the middle. But as pointed out in the answers, exit is a blunt instrument that you should only use when you want the program to end as fast as possible Commented Apr 3, 2024 at 0:25
  • 2
    You need validations for EVERY input. You may find cin input (input is an int) ... helpful regarding validating integer input with std::cin. (okay, cin >> character; is hard to screw up, but what happened to the '\n' generated by pressing the Enter key?) Commented Apr 3, 2024 at 0:27

2 Answers 2

1

Using exit(0) to terminate a program from within a function or an if statement is generally not recommended practice because it immediately terminates the entire program, bypassing any cleanup code or destructors that may need to run. It's considered sloppy because it's a blunt way of ending the program abruptly, and it can lead to resource leaks or other unexpected behavior.

Instead of using exit(0), using return 0; is preferable, especially if you're inside a function or the main() function. return allows the program to exit gracefully, executing any necessary cleanup code or destructors before terminating.

Some alternatives to using exit(0) or return to terminate the program include:

  1. Breaking out of loops using break statements.
  2. Setting flags or conditions to indicate when the program should terminate, and then exiting the loop or function based on those conditions.
  3. Throwing exceptions (if you're using a language that supports exceptions) to handle exceptional cases and gracefully exit the program.

Overall, using return instead of exit() promotes cleaner, more maintainable code by allowing the program to follow its normal control flow and handle termination gracefully.

Sign up to request clarification or add additional context in comments.

5 Comments

I am knew to c++ so what are some destructors I would know of? And what is a destructor if you don't mind answering? Thanks for your reply. Appreciate it!! Would you consider return valid in an if statement? Would most programmers agree with it? Im only asking because my professor said "Do not escape a loop early with any construct".
@tannerphillips It largely depends on the expectations of the code. Returning in if statements is considered valid, but it may be better-practice to not exit out of if statements (as it can become harder to debug later). I'd say if your professor says don't do it, try to avoid it at least for your classes. From one C++ learner to another!
@tannerphillips Do what you have to do to pass the course otherwise you're wasting your time and money. Some of the stuff you'll be taught will be academically valuable but professionally laughable (it's rare that you write your own linked list for example, but it's one of the best teaching tools around) and some stuff will be too ideologically rigid to survive contact with the real world, but as a student you want to learn to write code the right way. And I'll heap a lot of scorn on the instructors who teach programming the wrong way, but that doesn't seem to be the case here.
I will place a return in a loop if the result is easier to read and understand than the extra logic that needs to be added to avoid an early exit OR if testing finds the early exit saves enough time to meet a tight performance requirement.
> "Do not escape a loop early with any construct." Sounds to me like this particular prof doesn't want the class use any breaks either ? OP would need to confirm with them.
0

Using exit and return has a slightly different effect in terms of functionality. When a c++ program exits through exit(0), destructors for local nonstatic objects aren't called - if return 0 is used, destructors are called.

This can make a big difference because calling destructors is sometimes important, for example if it has code to close files, delete dynamically allocated memory, etc etc.

Overall, return is better and less dangerous, and is also more commonly used. Have fun coding!

Alternative solution: (thanks Yksisarvinen for the note)

If you don't want to escape out of a loop early at all, you can create a temporary boolean variable called ReturnOrNot (or some other name) and assign true to it if you need to quit.

Then, you can simply break out of the loop, check the variable and return if needed.

For example, with a dummy problem breaking when i is 3:

int i = 1;
bool returnornot = false;
while (i < 6) {
    if (i == 3) {
        returnornot = true;
        break;
    }
    i++;
}
if (returnornot) return 0;
// other code

1 Comment

However, the OP mentions 'Should I use a return rather than using exit?' which was the question I was answering. You make a good point, though, I'll add an alternative solution which doesn't require escaping the loop early.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.