Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

c - How can I get what my main function has returned?

In a C program if we want to give some input from terminal then we can give it by:

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

In the same way, if we want to get return value of main() function then how can we get it?

In each main() we write return 1 or return 0; how can I know what my main() has returned at terminal?

Edit:1

I get it that by echo $? we can get the return value of main() but it only allows me to return a value less then 125 (in Linux) successfully. A return value more than that cannot be be successfully received by the $ variable so

why is int the return type of main()? Why not keep it short int?

Edit2

From where can I find out the meaning of the error code if main() returns a value greater than 125?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Most shells store the exit code of the previous run command in $? so you can store or display it.

$ ./a.out
$ echo $?     # note - after this command $? contains the exit code of echo!

or

$ ./a.out
$ exit_code=$?    # save the exit code in another shell variable.

Note that under linux, although you return an int, generally only values less than 126 are safe to use. Higher values are reserved to record other errors that might occur when attempting to run a command or to record which signal, if any, terminated your program.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...