C++ question

Started by
2 comments, last by Tom Sloper 3 years, 11 months ago

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.

Advertisement

The main return value is the exit code of the program:

%  cat x.cc
int main() {
    return 21;
}

# Compile and run it
%  g++ -o x -Wall x.cc
%  ./x

# Ask the shell what exit code the program gave
%  echo $?
21

The ‘diff’ program for example uses that to communicate what the compare result was, from its manual “diff(1)”:

Exit status is 0 if inputs are the same, 1 if different, 2 if trouble

The standard says this runs through std::exit:

https://en.cppreference.com/w/cpp/language/main_function​​ (property number 5)

https://en.cppreference.com/w/cpp/utility/program/exit

This was posted accidentally in the Writing forum - it's now moved to the For Beginners forum.

Also, the question was posted twice. Locking this one.

-- Tom Sloper -- sloperama.com

This topic is closed to new replies.

Advertisement