MY adoration
关于单片机8个I/0口 实现36个按键功能

转载(留着慢慢看):void main(void) - the Wrong Thing

G-one posted @ 2010年3月25日 07:34 in program , 3097 阅读

 

void main(void) - the Wrong Thing

The newsgroup, comp.lang.c, is plagued by an almost continuous discussion of whether we can or cannot use void as a return type for main. The ANSI standard says "no", which should be an end of it. However, a number of beginners' books on C have used void main(void) in all of their examples, leading to a huge number of people who don't know any better.

When people ask why using a void is wrong, (since it seems to work), the answer is usually one of the following:

  • Because the standard says so.
    (To which the answer is usually of the form "but it works for me!")
  • Because the startup routines that call main could be assuming that the return value will be pushed onto the stack. If main() does not do this, then this could lead to stack corruption in the program's exit sequence, and cause it to crash.
    (To which the answer is usually of the form "but it works for me!")
  • Because you are likely to return a random value to the invokation environment. This is bad, because if someone wants to check whether your program failed, or to call your program from a makefile, then they won't be able to guarantee that a non-zero return code implies failure.
    (To which the answer is usually of the form "that's their problem").

This page demonstrates a system on which a void main(void) program will very likely cause problems in the third class above. Calling the program from a script may cause the script to die, whether or not its return code is checked. Calling it from a makefile may cause make to complain. Calling it from the command line may cause an error to be reported.

RISC OS is the native operating system of Acorn's range of ARM based computers. One of the facilities of this OS is a system variable, Sys$RCLimit. The value of this variable specifies the maximum value that a program may return to the OS without causing RISC OS itself to raise an error. The default value of this variable is set by the OS at 256. I'm not too sure what the intended function of this variable was, but it exists, and that's that.

Now, let's look at an example program using int main(void).
 

int main(void)
{
    return 42;
}

Compiling it to ARM assembly language, using gcc (as an aside: Acorn's own C compiler reports a warning with void main(void) and converts it to an integer function returning zero) gives the following:
 

|main|:
        mov     ip, sp  
        stmfd   sp!, {rfp, fp, ip, lr, pc}
        sub     fp, ip, #4
        cmps    sp,sl
        bllt    |x$stack_overflow|
        bl      |___main|

        mov     r0, #42
        ldmdb   fp, {rfp, fp, sp, pc}^


The first six instructions are initialisation and stack checking. The final two return 42 to the library startup code. So, the return value of main is passed in R0. Note that the library startup code is expecting to call a function returning an integer, so will happily use the value returned in R0.

What happens with a void main function? Well, here's an example.
 

#include <stdio.h>

char buf[1024];
void main(void)
{
	(void)fgets(buf, 1024, stdin);
}

The program waits for a line of text from its standard input, nothing else. Again we compile it to assembler:
 

|.LC0|:
        dcd     |__iob|
|.LC1|:
        dcd     |buf|
|main|:
        mov     ip, sp  
        stmfd   sp!, {rfp, fp, ip, lr, pc}
        sub     fp, ip, #4
        cmps    sp,sl
        bllt    |x$stack_overflow|
        bl      |___main|

        ldr     r2, [pc, #|.LC0| - . - 8]
        mov     r1, #1024
        ldr     r0, [pc, #|.LC1| - . - 8]

        bl      |fgets|

        ldmdb   fp, {rfp, fp, sp, pc}^

        area    |buf|, DATA, COMMON, NOINIT
        %       1024


Again, the first six instructions in main set things up. The next three set up the arguments for the call to fgets. Then we call fgets and return to the caller. stdio.h says that fgets returns a pointer to the buffer. So, in this instance, what we are returning to the library startup code is a pointer to buf. Under RISC OS, all C programs are mapped into memory at 0x8000. So, we will be returning a value to the OS which is > 32768 (hence, certainly > the default value of Sys$RCLimit). The OS then raises an error.

Here's the result of compiling and running the program:
 

SCSI: void % gcc void.c -o void
Drlink AOF Linker  Version 0.28  30/07/95
SCSI: void % show Sys$RCLimit
Sys$RCLimit : 256
SCSI: void % void
I enter this line
Return code too large
SCSI: void % 

And, in a script file:

SCSI: void % cat script

void
echo Finished

SCSI: void % run script
I enter this line
Return code too large
SCSI: void %


The error interrupts the script before the second command is run.

Note that the example above was a little contrived in order to make the final function call return a pointer. A better example where this could cause problems is one where the program uses printf to report a usage string > 256 characters long prior to returning or, worse still, one where the program uses printf to output data depending on user input. Depending on the length of the user's input text, the program may or may not cause an error which is solely due to the use of void as a return type for main.

So, if you want your software to be portable, please make main return int. It does matter.

Avatar_small
Anonymous 说:
2021年8月03日 22:56

I can recommend primarily decent and even responsible tips, as a result view it: فني ستلايت الكويت

Avatar_small
Anonymous 说:
2021年8月03日 23:01

I read this article. I think You put a great deal of exertion to make this article. I like your work.  مقوي سيرفس الكويت

Avatar_small
Anonymous 说:
2021年8月12日 01:37

It is quite beneficial, although think about the facts when it reaches this target. Tree removal in Long island Ny

Avatar_small
Anonymous 说:
2021年8月12日 02:11

I often take joy in finding a site that provides quality ideas because I like being familiar with interesting things. Very often when I have been to this website I have enjoyed the good article here. I'll be sure to watch out for your future write-up.. Thank you for the great posting I will revisit in the future. australia temporary phone number

Avatar_small
Anonymous 说:
2021年8月19日 14:58

I've proper selected to build a blog, which I hold been deficient to do for a during. Acknowledges for this inform, it's really serviceable! مكافحة القوارض

Avatar_small
Anonymous 说:
2021年8月19日 15:02

I use basically superior fabrics : you will discover these products by: رقم فني تكييف

Avatar_small
Anonymous 说:
2021年8月19日 15:07

I read this article. I think You put a lot of effort to create this article. I appreciate your work. بنشر متنقل

Avatar_small
Anonymous 说:
2021年8月19日 18:49

Excellent read, Positive site, where did u come up with the information on this posting?I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work. تصليح كهرباء منزل

Avatar_small
Anonymous 说:
2021年8月22日 15:58

I have a similar interest this is my page    read everything carefully and let me know what you think. تصليح طباخات

Avatar_small
Anonymous 说:
2021年8月23日 19:07

Finance We mix fully compliant strategies with captivating creative to push your business ahead of its competitors while staying on the right side of the FCA. Social Media Marketing

• Trade in electrical equipment Providing software services

• Trade in agricultural machinery and agricultural equipment

• Trade in agricultural products and food, fertilizers and plants

• Trade in construction materials

• Trade in metals, ferroalloys, graphite electrodes, deoxidizers, refractories and other additional materials connected with metal production

• Trade in spare car parts and equipment

• Trade in household appliances

• Light trading (textiles, clothing, footwear, haberdashery, dishes, jewelry, various accessories

• Sea container shipping of goods by our Panmax container carrier with a capacity of 4-7 thousand TEU Digital Solutions that Deliver Results

Digital Retail Graphic Design

Avatar_small
Anonymous 说:
2021年9月09日 20:30

So it is interesting and very good written and see what they think about other people.  استشارة قانونية

Avatar_small
Anonymous 说:
2021年9月13日 02:22

TechClient is an independent US-based web magazine dedicated to creating high-quality content from around the web – covering topics from technology to design.

TechClient provides useful digital tips and resources on software, apps and gadgets you can’t live without.

Avatar_small
Anonymous 说:
2021年9月15日 22:54

Listed here you'll learn it is important, them offers the link in an helpful webpage: wide area network definition

Avatar_small
Anonymous 说:
2021年9月17日 03:09

wow this saintly however ,I love your enter plus nice pics might be part personss negative love being defrent mind total poeple , 24 hour emergency los angeles plumber near me

Avatar_small
Anonymous 说:
2021年9月17日 03:13

Actually I read it yesterday but I had some thoughts about it and today I wanted to read it again because it is very well written. tree removal company

Avatar_small
Anonymous 说:
2021年9月17日 03:16

I should assert barely that its astounding! The blog is informational also always fabricate amazing entitys. personal injury attorneys

Avatar_small
Anonymous 说:
2021年9月17日 03:20

Initial You got a awesome blog .I determination be involved in plus uniform minutes. i view you got truly very functional matters , i determination be always checking your blog blesss. medical malpractice lawyers

Avatar_small
Anonymous 说:
2021年9月17日 03:24

I really appreciate this wonderful post that you have provided for us. I assure this would be beneficial for most of the people. Tree removal company

Avatar_small
Anonymous 说:
2021年9月20日 12:14

You ought to basically fantastic not to mention solid advice, which means notice: look at this site

Avatar_small
Anonymous 说:
2021年9月21日 01:24

I came onto your blog while focusing just slightly submits. Nice strategy for next, I will be bookmarking at once seize your complete rises... matterport chicago

Avatar_small
Anonymous 说:
2021年9月24日 02:41

In this article understand the most important thing, the item will give you a keyword rich link a great useful website page: ket qua xo so

Avatar_small
Anonymous 说:
2021年10月04日 14:50

Acknowledges for paper such a beneficial composition, I stumbled beside your blog besides decipher a limited announce. I want your technique of inscription... 먹튀검증커뮤니티

Avatar_small
Anonymous 说:
2021年10月04日 22:05

Welcome to the party of my life      here you will learn everything about me. 토토

Avatar_small
Anonymous 说:
2021年10月06日 02:04

I use basically superior fabrics : you will discover these products by: https://www.pcimag.com/articles/105832-drum-manufacturing-and-reconditioning-voc-control

Avatar_small
BSNL Customer Care n 说:
2022年8月08日 19:46

The new digital era based support system contributing a lion’s sharing related to all telecom services in 2021 calendar year, also find the new email address providing BSNL complaint process for payment failed issues for any digital payment service failure related issues like repayment, BSNL Customer Care number refund of debited amount and service activation /deactivation, complaints, tariff change requests.

Avatar_small
AP SSC fa 4 Question 说:
2022年9月09日 02:13

Formative Assessment means not only an examination, it includes various aspects such as Examination in completed lessons, Reflections, Project work done on the allotted topic and Self also Prepared notes etc. AP SSC fa 4 Question Paper Candidates of Telugu Medium, English Medium & Urdu Medium of the AP State can download the AP 10th Class FA 4 Model Paper 2023 Pdf with answers for the regular exams conducted by the Directorate of Government Examinations, Andhra Pradesh.

Avatar_small
Satta King fast 说:
2022年9月11日 18:11

Satta Kings is one such platform where people make bets online to win cash, as it can be one of the best and fastest ways to earn superfast cash. Satta King fast is of many types, and not just one. In this fashion you can place multiple betting positions at a time and have the next chance/hope to win, although it will always come back to you.

Avatar_small
Change Address in Pa 说:
2022年10月27日 00:24

International travel requires legal documentation that identifies you and the country you live in. Every country in the world has a set of regulations about the documents. Any visitor should present before settling in their country. Change Address in Passport A passport is a legal and mandatory document that is offered by an individual when traveling abroad. The document is issued by the government of a particular country the person lives in.

Avatar_small
FMS BSNL 说:
2023年2月07日 00:36

BSNL being traditional player and has many franchisees working under it. To establish a platform to all the franchisees or TIPs who is known as Telecom Infrastructure Providers, FMS BSNL make them work with ease, an online software tool calls BSNL Franchise Management System is being provided to manage their BSNL Bharat Fiber customer data base, for respective business and to get new business.

Avatar_small
www.questionspapers. 说:
2023年4月23日 09:42

Professional writers have joined forces to launch the questionspapers project, which provides in-depth news coverage of current events across the nation (India). Our team is made up of expert writers and citizen journalists that have a variety of journalismc www.questionspapers.in.interests and are passionate about publishing education updates in the public interest with transparency Our reporting team plans to release the Education & Recruitment Update for all age groups and provide inside coverage to show the real picture of current occurrences. As we want to provide news divided into General, Political, Crime, Sports, Entertainment, Education, and World News, our goal is to meet the needs of people of all age groups.

Avatar_small
https://pavzi.com/ 说:
2024年1月21日 01:00

Pavzi website is a multiple Niche or category website which will ensure to provide information and resources on each and every topic. Some of the evergreen topics you will see on our website are Career, Job Recruitment, Educational, Technology, Reviews and others. pavzi.com We are targeting mostly so it is true that Tech, Finance, and Product Reviews. The only reason we have started this website is to make this site the need for your daily search use.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter