首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

急关于return!解决方案

2012-04-13 
急!!!关于return!!!!!我在周公的书上多出看到在主函数main中有return0和return(1)而且定义了true为1,fals

急!!!关于return!!!!!
我在周公的书上多出看到在主函数main中有return   0和return   (1);而且定义了true为1,false为0,请问大侠什么意思???我对c语言不好!!!!

[解决办法]
当我们通过操作系统启动一个程序,程序执行完后,可以通过一些特殊的方式获得这个状态码。
比如在Windows命令行下通过
echo %ERRORLEVEL%
命令。

当然,更多的时候,我们根本不关心这个错误码,当程序出错时,我们可以通过更多的方式直接通知用户,比如显示一条错误消息,显示一个错误对话框,在文件输出一条log信息,等等。
[解决办法]
Typically the return value is used as a exit status code (I prefer to use the exit () function myself). So that, if your program is called by another program or a shell/batch script, the calling entity can react to the exit status appropriately.

To explain this a little more clearly, assume your program parses a large file and inserts the parsed data into a database. Your program is called by a user clicking a button in some other program. How does the user know if your program successfully completed the task? Or, if it was not completed successfully, why?

The easiest way to tell what happened after your program has completed is to check the returned exit status code. Most of the time these codes are defined by you. For instance, 0 if it completed okay, 1 if it could not connect to the database, 2 if it deadlocked with another user in the database, 3 if it couldn 't find the file to parse, etc. Then, using these codes, the calling program can print the appropriate message to the user 's screen, or use some sort of logic that will attempt to get your program to complete successfully.
[解决办法]
《c陷阱与缺陷》 --“ 为main函数提供返回值 ”


最简单的c程序也许是像下面这样



main()

{

}



这个程序包含一个不易察觉的错误。函数main与其他任何函数一样,如果并未显式声明返回类型,那么函数返回类型就默认为是整型。但是这个程序中并没有给出任何返回值。

通常说来,这不会造成什么危害。一个返回值为整型的函数如果返回失败,实际上是隐含地返回了某个“垃圾”整数。只要该数值不被用到。就无关紧要。

然而,在某些情形下函数main的返回值却并非无关紧要。大多数c语言实现都通过函数main的返回值来告知操作系统该函数的执行是成功还是失败。典型的处理方案是,返回值为0代表程序执行成功,返回值非0则表示程序执行失败。如果一个程序的main函数并不返回任何值,那么有可能看上去执行失败。如果正在使用一个软件管理系统,该系统关注程序被调用后执行是成功还是失败,那么很可能得到令人惊讶的结果。

严格说来,我们前面的最简单的c程序应该像下面这样编写代码:



main()

{

return 0;

}



或者写成



main()

{

exit( 0);

}



[解决办法]
并不是 0 代表不正常 1 代表正常

而是 false 代表不正常, true 代表正常

然而在c++里 false 的值刚好是 0 true 的值刚好是 1

true 和 false 是bool类型

main的返回值是int类型,不是同一类型

所以

main返回的 正常值是 0 (而不是false)

main的返回值不只表示成功和失败,还表示更多的信息,如前面发的英文解析


但对于一般函数,你可以通过返回0表示错误1表示正确,

但最好显示写false ,true
[解决办法]
《C How to Programming》
《C语言解析教程》
当然,如果找到《C语言大全》是最好,可惜已经绝版。

热点排行