C++问题汇总

发布时间 2023-09-26 08:06:52作者: ChrainY

主函数的return是如何使用的?

In C++, the main function can return an integer value, typically used to indicate the success or failure of the program. By convention:

  • Returning 0 indicates success.
  • Returning a non-zero value indicates an error or abnormal termination.

Here's a simple example:

#include <iostream>

int main() {
    int choice;

    std::cout << "Choose an option:\n";
    std::cout << "1. Continue\n";
    std::cout << "2. Exit with error\n";
    std::cin >> choice;

    if (choice == 1) {
        std::cout << "Program continues...\n";
        // ... other code ...

        return 0;  // Indicates successful termination
    } else if (choice == 2) {
        std::cout << "Exiting with an error code...\n";
        return 1;  // Indicates an error
    } else {
        std::cout << "Invalid choice!\n";
        return -1; // Another error code
    }
}

When you run this program, you can choose an option. If you choose option 1, the program will return 0, indicating a successful termination. If you choose option 2, the program will return 1, indicating an error. Any other choice will return -1.

If you're using Linux, you can check the return value of your program in the terminal (on Unix-like systems) by running the program and then using the echo $? command. This will display the return value of the last executed command, which in this case would be your program.

If you're using Windows 10, you can check the return value of a program using the Command Prompt.

Here's how you can do it:

  1. First, compile your C++ program. Let's say you've named it my_program.cpp. Using the g++ compiler, you'd compile it like this:
g++ my_program.cpp -o my_program.exe
  1. After compiling, run your program:
my_program.exe
  1. Once your program has finished executing, you can check its return value using the echo command with the %ERRORLEVEL% environment variable:
echo %ERRORLEVEL%

This will display the return value of your program. For example, if your program returned 1, the command will display 1.

Remember, in the context of the previous example:

  • A return value of 0 indicates success.
  • A return value of 1 indicates an error (from option 2).
  • A return value of -1 indicates another error (from an invalid choice).