This question already has answers here:
What should main() return in C and C++?
(19 answers)
Closed 9 years ago.
I am currently reading what functions are in c++. It says that they are "artifacts that enable you to divide the content of your application into functional units that can be invoked in a sequence of your choosing.A function, when invoked, typically returns a value to the calling function."
It then goes on to say that main() is recognized by the compiler as the starting point of your c++ application and has to return an int (integer).
I don't know what is meant by 'has to return an integer'. From my (extremely limited experience) int main () is the start of your application. But what is meant by 'has to return an int'?. This is also intertwined with me not understanding 'typically returns a value to the calling function'
Just like in mathematics, in C++ functions return values. All functions in C++ must specify exactly what type of value they return, and every function must return only one type of thing. In some cases, that "one type of thing" might be nothing, which is denoted in C++ with the keyword void.
Every function must declare what it returns. This is done via a function declaration. Here are several examples:
int foo();
void bar();
string baz();
int main();
4 function declarations. foo returns an int, bar returns nothing, baz returns a string (which is declared in the C++ Standard Library), and main returns an int.
Not only must every function declare what it returns, it must also return that type of thing. If your function returns void, then you can write:
void bar()
{
return;
}
...or just do nothing:
void bar()
{
}
If your function returns anything other than void, then you have to have a return statement that returns that type of thing:
int foo()
{
return 42;
}
If you declare a function to return one type of thing, but then try to return another type of thing, then either there must be a way to implicitly convert from whatever you're trying to convert to what the function is declared to return. If there is no possible implicit conversion, your program won't compile. Consider:
int foo()
{
return "foobar rulez!";
}
Here, foo is declared to return an int, but I'm trying to return a string (not a string from the Standard Library, but an old C-style const char* string. `"foobar rulez!" here is called a string literal.)
It is possible to write code to provide the implicit conversion I mentioned earlier, but unless you know exactly why you want to do that it's better to not get mixed up in all that right now.
What do you do with the values that are returned from functions? Again, just like with mathematics, you can use those values somewhere else in your program.
#include <cstdlib>
#include <iostream>
int foo()
{
return 42;
}
int main()
{
int answer = foo();
std::cout << "The answer to Life, the Universe and Everything is...\n"
<< answer << "!\n";
return 0;
}
Obviously you can't do anything with the value that is returned from a function that returns void, because a function that returns void doesn't really return anything at all. But these kinds of functions are useful for doing stuff kind of on the side.
#include <cstdlib>
#include <iostream>
int theAnswer = 0;
void DeepThought()
{
theAnswer = 42;
}
int foo()
{
return theAnswer;
}
int main()
{
DeepThought();
int answer = foo();
std::cout << "The answer to Life, the Universe and Everything is...\n"
<< answer << "!\n";
return 0;
}
OK, back to all this business with main.
main is a function in C++. There are a few things about main that make it special compared to other functions in C++, and two of those things are:
Every program must have exactly one function called main() (in global scope).
That function must return an int
There is one more thing about main that's a little special and possibly confusing. You don't actually have to write a return statement in main*, even though it is declared to return an int. Consider:
int main()
{
}
Note that there's no return statement here. That is legal and valid in C++ for main, but main is the only function where this is allowed. All other functions must have an explicit return statement if they don't return void.
So what about the return value from main()? When you run a program on an Windows or Linux computer, the program returns a value to the operating system. What that value means depends on the program, but in general a value of 0 means that the program worked without any problems. A value other than 0 often means that the program didn't work, and the exact value is actually a code for what went wrong.
Scripts and other programs can use these return values to decide what to do next. For example, if you wrote a program to rename an MP3 file based on the Artist and track Number, then your program might return 0 if it worked, 1 if it couldn't figure out the Artist, and 2 if it couldn't figure out the Track Number. You can call this function in a script that renames and then moves files. If you want your script to quit if there was an error renaming the file, then it can check these return values to see if it worked or not.
no explicit return statement in main: In cases where main does not have an explicit return, it is defined to return the value 0.
Although it may appear so when you are programming in C or C++, main is not actually the "first thing" that happens. Typically, somewhere in the guts of the C or C++ runtime library is a call to main, which starts your program. When your program is finished and returns from main, it will return a value (in C++, if you don't specify something, the compiler will automatically add return 0), and this return value is used to signal "the success" of the program.
In Unix/Linux etc, this is used as $?, so you can echo $? after running a program to see what the "result" was - 0 means "went well", other values are used for "failure". In windows, there is a ERRORLEVEL variable in batch scripts, etc, that can be used to see the result of the last command.
Edit: If your code calls another program, e.g. through CreatProcess in Windows, or fork()/exec() in a Unix style OS (or the C runtime functions spawn and siblings in almost any OS), the return value from main is the new process finishes, and made available for the owning process. End Edit.
Since, even in C++, main is a "C" style function, if you change the return type, it still has the same name, so the linker/compiler can't "detect" that it's got the wrong return type, and some weird stuff will happen if you declare void main(), std::string main() or float main() or something other than int main() - it will still compile, but what happens in the code calling main will be undefined behaviour - this means "almost anything can happen".
This is how you report back to the operating system the exit status of the program, whether it ran successfully or not. For example in Linux you can use the following command:
echo $?
to obtain the the exit status of the program that ran previously.
Yes, main should always returns an int, this can be used to show if the program runs successfully, usually 0 represents sucess, a non-zero value represents some kind of failure.
For example, in Linux, you can call your program in a bash script, and in this script, run different commands on the return status of your program.
It means, in the signature of main() the return type is int:
int main();
int main(int argc, char const *argv[]);
Now what value you would return from main(), is the question. Well, the return value is actually exit status which indicates to the runtime whether the main() executes sucessfully or unsuccessfully.
In Linux, I usually return EXIT_SUCCESS or EXIT_FAILURE depending on the cases. These are macros defined by <cstdlib>.
int main()
{
//code
if ( some failure condition )
return EXIT_FAILURE;
//code
return EXIT_SUCCESS;
}
As per the doc:
#define EXIT_SUCCESS /*implementation defined*/
#define EXIT_FAILURE /*implementation defined*/
The EXIT_SUCCESS and EXIT_FAILURE macros expand into an integral expression and indicate program execution status.
Constant Explanation
EXIT_SUCCESS successful execution of a program
EXIT_FAILURE unsuccessful execution of a program
Related
I was taught that functions need declarations to be called. To illustrate, the following example would give me an error as there is no declaration for the function sum:
#include <iostream>
int main() {
std::cout << "The result is " << sum(1, 2);
return 0;
}
int sum(int x, int y) {
return x + y;
}
// main.cpp:4:36: error: use of undeclared identifier 'sum'
// std::cout << "The result is " << sum(1, 2);
// ^
// 1 error generated.
To fix this, I'd add the declaration:
#include <iostream>
int sum(int x, int y); // declaration
int main() {
std::cout << "The result is " << sum(1, 2);
return 0;
}
int sum(int x, int y) {
return x + y;
}
Why the main function doesn't need the declaration, as other functions like sum need?
A definition of a function is also a declaration of a function.
The purpose of a declaring a function is to make it known to the compiler. Declaring a function without defining it allows a function to be used in places where it is inconvenient to define it. For example:
If a function is used in a source file (A) other than the one it is defined in (B), we need to declare it in A (usually via a header that A includes, such as B.h).
If two or more functions may call each other, then we cannot define all those functions before the others—one of them has to be first. So declarations can be provided first, with definitions coming afterward.
Many people prefer to put “higher level” routines earlier in a source file and subroutines later. Since those “higher level” routines call various subroutines, the subroutines must be declared earlier.
In C++, a user program never calls main, so it never needs a declaration before the definition. (Note that you could provide one if you wished. There is nothing special about a declaration of main in this regard.) In C, a program can call main. In that case, it does require that a declaration be visible before the call.
Note that main does need to be known to the code that calls it. This is special code in what is typically called the C++ runtime startup code. The linker includes that code for you automatically when you are linking a C++ program with the appropriate linker options. Whatever language that code is written in, it has whatever declaration of main it needs in order to call it properly.
I was taught that functions need declarations to be called.
Indeed. A function must be declared before it can be called.
why we don't add a declaration for the main function?
Well, you didn't call main function. In fact, you must not call main at all1, so there is never a need to declare main before anything.
Technically though, all definitions are also declarations, so your definition of main also declares main.
Footnote 1: The C++ standard says it's undefined behaviour to call main from within the program.
This allows C++ implementations to put special run-once startup code at the top of main, if they aren't able to have it run earlier from hooks in the startup code that normally calls main. Some real implementations do in fact do this, e.g. calling a fast-math function that sets some FPU flags like denormals-are-zero.
On a hypothetical implementation, calling main could result in fun things like re-running constructors for all static variables, re-initializing the data structures used by new/delete to keep track of allocations, or other total breakage of your program. Or it might not cause any problem at all. Undefined behaviour doesn't mean it has to fail on every implementation.
The prototype is required if you want to call the function, but it's not yet available, like sum in your case.
You must not call main yourself, so there is no need to have a prototype. It's even a bad a idea to write a prototype.
No, the compiler does not need a forward declaration for main().
main() is a special function in C++.
Some important things to remember about main() are:
The linker requires that one and only one main() function exist when creating an executable program.
The compiler expects a main() function in one of the following two forms:
int main () { /* body */ }
int main (int argc, char *argv[]) { /* body */ }
where body is zero or more statements
An additional acceptable form is implementation specific and provides a list of the environment variables at the time the function is called:
int main (int argc, char* argv[], char *envp[]) { /* body */ }
The coder must provide the 'definition' of main using one of these acceptable forms, but the coder does not need to provide a declaration. The coded definiton is accepted by the compiler as the declaration of main().
If no return statement is provided, the compiler will provide a return 0; as the last statement in the function body.
As an aside, there is sometimes confusion about whether a C++ program can make a call to main(). This is not recommended. The C++17 draft states that main() "shall not be used within a program." In other words, cannot be called from within a program. See e.g. Working Draft Standard for C++ Programming Language, dated "2017-03-21", Paragraph 6.6.1.3, page 66. I realize that some compilers support this (including mine), but the next version of the compiler could modify or remove that behavior as the standard uses the term "shall not".
It is illegal to call main from inside your program. That means the only thing that is going to call it is the runtime and the compiler/linker can handle setting that up.This means you do not need a prototype for main.
A definition of a function also implicitly declares it. If you need to reference a function before it is defined you need to declare it before you use it.
So writing the following is also valid:
int sum(int x, int y) {
return x + y;
}
int main() {
std::cout << "The result is " << sum(1, 2);
return 0;
}
If you use a declaration in one file to make a function known to the compiler before it is defined, then its definition has to be known at linking time:
main.cpp
int sum(int x, int y);
int main() {
std::cout << "The result is " << sum(1, 2);
return 0;
}
sum.cpp
int sum(int x, int y) {
return x + y;
}
Or sum could have its origin in a library, so you do not even compile it yourself.
The main function is not used/referenced in your code anywhere, so there is no need to add the declaration of main anywhere.
Before and after your main function the c++ library might execute some init and cleanup steps, and will call your main function. If that part of the library would be represented as c++ code then it would contain a declaration of int main() so that that it could be compiled. That code could look like this:
int main();
int __main() {
__startup_runtime();
main();
__cleanup_runtime();
}
But then you again have the same problem with __main so at some point there is no c++ anymore and a certain function (main) just represents the entry point of your code.
Nope. You can't call it anyway.
You only need forward declarations for functions called before they are defined. You need external declarations (which look exactly like forward declarations on purpose) for functions defined in other files.
But you can't call main in C++ so you don't need one. This is because the C++ compiler is allowed to modify main to do global initialization.
[I looked at crt0.c and it does have a declaration for main but that's neither here nor there].
How to cout the return value of the main function "main()"? I just want to check if the return value of main function is really "0" when it is successfully executed.
Thank you!
You can use a unix command to check the return value of the previously executed command, in this case your c program.
echo $?
The shell variable $? is the return code of the previous command.
How to find the return value of last executed command in UNIX?
If you want to check the value within the code, just cout the value right before the return.
Do you mean you want to test that the following returns 0?
int main() {
int rc = doSomething();
return rc;
}
You can do it like this:
int main() {
int rc = doSomething();
std::cout << rc << "\n"; // Just print it out before returning
return rc;
}
But it's better to check the return value in the shell from where you run your application:
On UNIX/Linux (in shell):
> ./my_app
> echo $?
0
On Windows (in command prompt):
> my_app.exe
> echo %ERRORLEVEL%
Note that in C++ you are not allowed to intercept the call to main() or call it yourself.
3.6.1 Main function
The function main shall not be used within a program.
So you should not attempt to wrap the main() call and print its return value. Even if that works, it would not be portable (not to mention you'd actually end up running your application twice).
main is special, mostly because you can't call it yourself. The value that it returns is passed back to the operating system, which does whatever is appropriate. The C++ standard can't dictate how the OS treats various return values, so it provides an abstraction: you can use return EXIT_SUCCESS to indicate success, and you can use return EXIT_FAILURE to indicate failure. (You can also use return 0 to mean return EXIT_SUCCESS; the program's runtime system has to handle this correctly). The values of the macros EXIT_SUCCESS and EXIT_FAILURE are suitable for the OS that the program was compiled for. While 0 is the typical value for EXIT_SUCCESS, it's certainly possible for an OS to require a different value, and EXIT_SUCCESS will have the appropriate value for that OS. So even if you could check the value returned from main it wouldn't tell you much, without also knowing what value the OS expects from a successful program.
Type the other function after main(), then type main(); in that function
One problem though, main will be the first function to be called automatically. Although, i'm sure there is a way to fix it. This is how you call main or return main.
Hope this helps.
int main() {
int i = 5;
cout << i;
}
int second() {
main();
}
Welcome to Stack Overflow!
If it's 0, then it's 0. You are the one who specify the return value of your own function. If you are unsure, please add code and/or problem, which is bothering you.
What if I define main as a reference to function?
#include<iostream>
#include<cstring>
using namespace std;
int main1()
{
cout << "Hello World from main1 function!" << endl;
return 0;
}
int (&main)() = main1;
What will happen? I tested in an online compiler with error "Segmentation fault":
here
And under VC++ 2013 it will create a program crashing at run-time!
A code calling the data of the function pointer as a code will be compiled which will immediately crash on launch.
I would also like an ISO C++ standard quote about this.
The concept will be useful if you want to define either of 2 entry-points depending on some macro like this:
int main1();
int main2();
#ifdef _0_ENTRY
int (&main)() = main1;
#else
int (&main)() = main2;
#endif
That's not a conformant C++ program. C++ requires that (section 3.6.1)
A program shall contain a global function called main
Your program contains a global not-a-function called main, which introduces a name conflict with the main function that is required.
One justification for this would be it allows the hosted environment to, during program startup, make a function call to main. It is not equivalent to the source string main(args) which could be a function call, a function pointer dereference, use of operator() on a function object, or construction of an instance of a type main. Nope, main must be a function.
One additional thing to note is that the C++ Standard never says what the type of main actually is, and prevents you from observing it. So implementations can (and do!) rewrite the signature, for example adding any of int argc, char** argv, char** envp that you have omitted. Clearly it couldn't know to do this for your main1 and main2.
This would be useful if you want to define either of 2 entry-points depending on some macro
No, not really. You should do this:
int main1();
int main2();
#ifdef _0_ENTRY
int main() { return main1(); }
#else
int main() { return main2(); }
#endif
This is soon going to become clearly ill-formed, thanks to the resolution of CWG issue 1886, currently in "tentatively ready" status, which adds, among other things, the following to [basic.start.main]:
A program that declares a variable main at global scope or that
declares the name main with C language linkage (in any namespace) is
ill-formed.
What will happen in practice is highly dependent on the implementation.
In your case your compiler apparently implements that reference as a "pointer in disguise". In addition to that, the pointer has external linkage. I.e. your program exports an external symbol called main, which is actually associated with memory location in data segment occupied by a pointer. The linker, without looking too much into it, records that memory location as the program's entry point.
Later, trying to use that location as an entry point causes segmentation fault. Firstly, there's no meaningful code at that location. Secondly, a mere attempt to pass control to a location inside a data segment might trigger the "data execution protection" mechanisms of your platform.
By doing this you apparently hoped that the reference will get optimized out, i.e. that main will become just another name for main1. In your case it didn't happen. The reference survived as an independent external object.
Looks like you already answered the question about what happens.
As far as why, in your code main is a reference/pointer to a function. That is different than a function. And I would expect a segment fault if the code is calling a pointer instead of a function.
I am very new to programming and am confused about what void does, I know that when you put void in front of a function it means that "it returns nothing" but if the function returns nothing then what is the point of writing the function?? Anyway, I got this question on my homework and am trying to answer it but need some help with the general concept along with it. any help would be great, and please try to avoid technical lingo, I'm a serious newb here.
What does this function accomplish?
void add2numbers(double a, double b)
{
double sum;
sum = a + b;
}
void ReturnsNothing()
{
cout << "Hello!";
}
As you can see, this function returns nothing, but that doesn't mean the function does nothing.
A function is nothing more than a refactoring of the code to put commonly-used routines together. If I'm printing "Hello" often, I put the code that prints "Hello" in a function. If I'm calculating the sum of two numbers, I'll put the code to do that and return the result in a function. It's all about what you want.
There are loads of reasons to have void functions, some of these are having 'non pure' side effects:
int i=9;
void f() {
++i;
}
In this case i could be global or a class data member.
The other is observable effects
void f() {
std::cout <<"hello world" << std::endl;
}
A void function may act on a reference or pointer value.
void f(int& i) {
++i;
}
It could also throw, although don't do this for flow control.
void f() {
while(is_not_broke()) {
//...
}
throw std::exception(); //it broke
}
The purpose of a void function is to achieve a side effect (e.g., modify a reference parameter or a global variable, perform system calls such as I/O, etc.), not return a value.
The use of the term function in the context of C/C++ is rather confusing, because it disagrees wiht the mathematical concept of a function as "something returning a value". What C/C++ calls functions returning void corresponds to the concept of a procedure in other languages.
The major difference between a function and a procedure is that a function call is an expression, while a procedure call is a statement While functions are invoked for their return value, procedures are invoked for their side effects (such as producing output, changing state, and so on).
A function with void return value can be useful for its side effects. For example consider the standard library function exit:
void exit(int status)
This function doesn't return any value to you, but it's still useful for its side-effect of terminating the process.
You are on the right lines - the function doesn't accomplish anything, because it calculates something but that something then gets thrown away.
Functions returning void can be useful because they can have "side effects". This means something happens that isn't an input or output of the function. For example it could write to a file, or send an email.
Function is a bit of a missnomer in this case; perhaps calling it a method is better. You can call a method on an object to change its state, i.e. the values of it's fields (or properties). So you might have an object with properites for x and y coordinates and a method called Move which takes parameters xDelta and yDelta.
Calling Move with 2, 3 will cause 2 to be added to your X property and 3 to be added to your Y property. So the state of the object has changed and it wouldn't have made musch sense for Move to have returned a value.
That function achieves nothing - but if you had written
void add2numbers(double a, double b, double &sum)
{
sum = a + b;
}
It would give you the sum, whether it's easier to return a value or use a parameter depends on the function
Typically you would use a parameter if there are multiple results but suppose you had a maths routine where an answer might not be possible.
bool sqrt(double value, double &answer)
{
if value < 0.0 ) {
return false;
} else {
answer = real_sqrt_function(value);
return true;
}
}
I currently use a visualization library called VTK. I normally write void functions to update some part of the graphics that are displayed to the screen. I also use void functions to handle GUI interaction within Qt. For example, if you click a button, some text gets updated on the GUI.
You're completely right: calculating a function that returns nothing is meaningless – if you're talking about mathematical functions. But like with many mathematical concepts, "functions" are in many programming languages only related to mathematical functions, but behave more or less subtly different.
I believe it's good to explain it with a language that does not get it wrong: one such language is Haskell. That's a purely functional language which means a Haskell function is also a mathematical function. Indeed you can write Haskell functions much more mathematical-styled, e.g.
my_tan(x) = sin(x)/cos(x) -- or (preferred): tan' x = sin x / cos x
than in C++
double my_tan(double x) { return sin(x)/cos(x); }
However, in computer programs you don't just want to calculate functions, do you? You also want to get stuff done, like displaying something on your screen, sending data over the network, reading values from sensors etc.. In Haskell, things like these are well separated from pure functions, they all act in the so-called IO monad. For instance, the function putStrLn, which prints a line of characters, has type String -> IO(). Meaning, it takes a String as its argument and returns an IO action which prints out that string when invoked from the main function, and nothing else (the () parens are roughly what's void in C++).
This way of doing IO has many benefits, but most programming languages are more sloppy: they allow all functions to do IO, and also to change the internal state of your program. So in C++, you could simply have a function void putStrLn(std::string), which also "returns" an IO action that prints the string and nothing else, but does not explicitly tell you so. The benefit is that you don't need to tie multiple knots in your brain when thinking about what the IO monad actually is (it's rather roundabout). Also, many algorithms can be implemented to run faster if you have the ability to actually tell the machine "do this sequence of processes, now!" rather than just asking for the result of some computation in the IO monad.
I want to use longjmp to simulate goto instruction.I have an array DS containing elements of struct types (int , float, bool ,char). I want to jump to the place labled "lablex" where x is DS[TOP].int_val. how can I handle this?
sample code :
...
jmp_buf *bfj;
...
stringstream s;s<<"label"<<DS[TOP].int_val;
bfj = (jmp_buf *) s.str();
longjmp(*bfj,1);
but as I thought it's having problem what should I do?
error:
output.cpp: In function ‘int main()’:
output.cpp:101: error: invalid cast from type ‘std::basic_string, std::allocator >’ to type ‘__jmp_buf_tag (*)[1]’
You probably don't want to use longjmp at all but I hate it when people answer a question with "Why would you want to do that?" As has been pointed out your longjmp() usage is wrong. Here is a simple example of how to use it correctly:
#include <setjmp.h>
#include <iostream>
using namespace std;
jmp_buf jumpBuffer; // Declared globally but could also be in a class.
void a(int count) {
// . . .
cout << "In a(" << count << ") before jump" << endl;
// Calling longjmp() here is OK because it is above setjmp() on the call
// stack.
longjmp(jumpBuffer, count); // setjump() will return count
// . . .
}
void b() {
int count = 0;
cout << "Setting jump point" << endl;
if (setjmp(jumpBuffer) == 9) return;
cout << "After jump point" << endl;
a(count++); // This will loop 10 times.
}
int main(int argc, char *argv[]) {
b();
// Note: You cannot call longjmp() here because it is below the setjmp() call
// on the call stack.
return 0;
}
The problems with your usage of longjmp() are as follows:
You don't call setjmp()
You haven't allocated the jmp_buf either on the stack or dynamically. jmp_buf *bfj is just a pointer.
You cannot cast a char * to jmp_buf * and expect it to work. C++ not a dynamic language it is statically compiled.
But really, it is very unlikely that you should be using longjmp() at all.
The normal way to use longjump is incombination with setjump() as described here. You seem to want to make a jumptable as normally done with switch-case or with virtual functions.
Anyway, labels in code (compile-time) are not reachable with strings (run-time), so that is already your first problem. You would really need to find out the address of where you want to jump to and my best guess would be to put setjump()'s where your labels are.
You've totally failed C++. Firstly, goto's are bad, and not for the uninitiated- there's a reason that for, while, break, continue etc exist. Secondly, you're trying to convert a string into an identifier, which is impossible at runtime unless you code it yourself. Thirdly, you're.. trying to cast a const char* to a jmp_buf*? What?
In addition to that, C++ does have goto. But if you want to jump given an int, then you're going to have to switch it, e.g.
switch (DS[TOP].int_val) {
case 1:
goto label1;
break;
case 2:
goto label2;
break;
default:
throw std::runtime_error("Unrecognized label!");
}
Sounds like you want a function pointer:
((void(*)(void))*((int *)DS[TOP].int_val))();
This treats DS[TOP].int_value like an address and jumps to it. If you wanted to jump to where DS[TOP].int_value is located, you would:
((void(*)(void))*((int *)&DS[TOP].int_val))();
Either way, ugly, ugly code. But it should do what you want.
When setjmp() is called, the system effectively takes a snapshot of the call and parameter stack. This snapshot will remain valid until user code exits the block in which setjmp() was called; if longjmp() is called with that snapshot, execution will resume as though the setjmp() were returning for the first time, except that instead of returning zero, it will return the second parameter passed to longjmp(). It is very important to note that calling longjmp() with an invalid snapshot may have very bad effects. In some systems, such an invalid call may "seem" to work, but corrupt the system in such a way that it later crashes.
Although setjmp()/longjmp() are sometimes appropriate in pure C programs, having a C program call setjmp() to create a snapshot, and then call some C++ code which in turn calls longjmp() to return to that snapshot, is a recipe for disaster. Nearly all situations where one would want to do that may be better handled using exceptions.