Skip to main content
GameDev.net gamedev.net
🔒 Locked

C++ question

Started by JeraldtheBEAR Jun 12, 2020 at 11:36 PM 16 replies 14.8k views
Original Post
JeraldtheBEAR
JeraldtheBEAR

This is a very basic question. In int main() why is it a int and not a void and why do you have to return 0.

#include <iostream> // The # represens a preprocessor directive and <iostream is a header file>

int main() 
{  
    //std stands for standard
    std::cout << "You are a secret agent breaking into a secure server room...";
    std::cout << std::endl; //endl means end line
    std::cout << "You need to enter the correct codes to continue...";

    const int a = 4;
    const int b = 3;
    const int c = 2;


    const int sum = a + b + c;
    const int product = a * b * c;


    std::cout << std::endl;
    std::cout << sum << std::endl;
    std::cout << product << std::endl;

return 0;

    //use std::cout << std::endl for new line
}

Don't mind the comments. I am taking a udemy class and it says you have to return 0. Why did they say that. Thanks for the help.

Rutin
Rutin

Having return 0 means the program as exited as expected. I personally don't even put return 0; in main as it can be omitted with C++. However other functions will require a return statement.

int addSomething(int a, int b) { return a + b; } // GOOD
int addSomething(int a, int b) {  } // ERROR: Function must return a value

You can have main as follows:

int main(int argc, char *argv[]) { }
int main() { }

You can omit return 0 because if you don't write a return statement it will by default.

Programmer and 3D Artist
h8CplusplusGuru
h8CplusplusGuru

A zero error code typically means there was no error. With a non-zero, you would look up that code to figure out the problem.

Tom Sloper
Tom Sloper

Wrong forum (it has now been moved to a more appropriate forum).

-- Tom Sloper    --      sloperama.com
frob
frob

JeraldtheBEAR said:
Why did they say that. Thanks for the help.

Historically programs return values to the operating system. It has been that way since systems dating back to the 1960s and earlier.

Your main() function returns a value to the OS to signal result codes. Usually for commands from the system 0 indicates success, and positive values indicate standard error codes set by the OS. The return codes are not universal, as programs like the Unix tool ‘count’ return the number of items rather than returning 0 for success. Some programs like the Windows tool ‘robocopy' return more complex error codes as bitflags; values 0-7 indicate success by setting any of the bits meaning no copying was done, or files were only added, or extra files were removed, or mismatched files were detected and copied, but all of them meaning the copy command robustly handled what was expected, values with higher bits set (values 8 or above) mean other errors happened and the command failed.

You can choose what your program returns to the operating system. This can help you write scripting tools later on which use your program as one step among many.

Rutin said:
You can omit return 0 because if you don't write a return statement it will by default.

This is a legacy feature from the 1970s and the early C language. If you do not return anything, the value 0 will be returned by the operating system.

It is classified as an intentional exception that has been included in the language, and requests to change it in language defect reports have been rejected since the beginning. The main() function is the only exception to the rule, a function specified as returning a value but then legally not returning one.

For any other function this is undefined behavior. A program might not compile, might happen to work correctly in one case, might crash, might have hidden bugs, might corrupt the stack, might allow for hacker exploits, or might even wipe the hard drive, all the regular undefined behavior warnings apply.

Rutin
Rutin

frob said:
This is a legacy feature from the 1970s and the early C language. If you do not return anything, the value 0 will be returned by the operating system. It is classified as an intentional exception that has been included in the language, and requests to change it in language defect reports have been rejected since the beginning. The main() function is the only exception to the rule, a function specified as returning a value but then legally not returning one. For any other function this is undefined behavior. A program might not compile, might happen to work correctly in one case, might crash, might have hidden bugs, might corrupt the stack, might allow for hacker exploits, or might even wipe the hard drive, all the regular undefined behavior warnings apply.

I wasn't sure if you are responding to my comment or explaining why I said you can omit ‘return 0;’ in the main function.

For clarification, my comment was only referring to main() which is why I wrote above how you must a return a value in any other function, but can omit it from main().

Programmer and 3D Artist
Prototype
Prototype

Our first PC at home (an early IBM-clone) was installed with some office software that relied heavily on batch files and the return codes from the individual executables. There even was a YESNO.COM that would ask for user input and more of that. It was more or less an attempt at modular programming.

So for the first couple of months I thought that was the way how PC's are programmed and it kind of bothered me, but nevertheless I became quickly proficient in building batch files ?

jbb
jbb

When your program returns from main it's as if it called the exit function with the value you returned.
See https://en.cppreference.com/w/cpp/utility/program/exit

(With some additional differences, see the relationship with main function in the link above).

If you run the program from a command line prompt, in windows you can test the return value using the ERRORLEVEL command in a batch file or $? in a unix shell.

You can return an int but the only values you should return if you want somewhat portable code are EXIT_SUCESS and EXIT_FAILURE (defined in stdlib.h)

Bazzy_505
Bazzy_505

JeraldtheBEAR said:

This is a very basic question. In int main() why is it a int and not a void and why do you have to return 0.

void myAwesmeFunction() { // your code };

used to declare functions. In a basic sense. whatever you put in curly braces is not executed unless if it called within

int main() { // your code }

int main() where execution of your code ( { ) always begins and and ends., all you want to do is called from within( }; ).

fleabay
fleabay

JeraldtheBEAR said:
This is a very basic question. In int main() why is it a int and not a void and why do you have to return 0.

Learning some Google skills will go a long way towards learning C++. You should start with a good book though. A good book would have explained this in chapter one.

Googling “c++ main return value” gives the same information in this thread and more. The more you Google for things you don't know, the more you learn in the process.

🙂🙂🙂🙂🙂<←The tone posse, ready for action.
8Observer8
8Observer8

It is difficult to remember what you must to return 0 or 1. Return EXIT_SUCCESS or EXIT_FAILURE. This macros contains 0 and 1 respectively.

#include <iostream>

int main()
{
    std::cout << "Hello World!" << std::endl;

    bool isError = false;
    if (isError)
    {
        std::cerr << "Error message" << std::endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}
8Observer8
8Observer8

I think it is right for Qt console application, isn't it?

#include <QCoreApplication>
#include <iostream>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    std::cout << "Hello World!" << std::endl;

    bool isError = true;
    if (isError)
    {
        std::cerr << "Error message" << std::endl;
        return EXIT_FAILURE;
    }

    return a.exec();
}
Alberth
Alberth

Bazzy_505 said:
void myAwesmeFunction() { // your code };

Please be careful here. This is not a complete function, as the closing curly bracket is comment text. Either use 2 lines, or a block comment like

void may_awesome_function() { /* your code */ }; // C++ typically doesn't use camelcase for functions.
Alberth
Alberth

Prototype said:
There even was a YESNO.COM that would ask for user input and more of that. It was more or less an attempt at modular programming.

I think they tried to simulate a Unix shell, except it failed horribly as the COMMAND program was too weak compared to a Unix shell, and lack of multi-tasking pretty much broke any attempt to use pipes.

fleabay
fleabay

Alberth said:
C++ typically doesn't use camelcase for functions.

Yes it does. Why would you say that, even as part of an example comment?

🙂🙂🙂🙂🙂<←The tone posse, ready for action.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.