从C中的int函数返回一个值 [英] Returning a value from an int function in C
本文介绍了从C中的int函数返回一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在C中有一个int函数,我想出了一个问题。
要启动这里是我的工作!
代码:
I have an int function in C and I came up with a question.
To start up here's is my working!
code:
int count_numbers(FILE *input) {
int count = 0;
fscanf(input, "%d",&count);
if(count < 1 || count > 30)
exit(2);
else
return count;
}
如果可能的话,我想让代码更干净:
and I wanted to make the code cleaner if possible trying this:
int count_children(FILE *input) {
int count = 0;
fscanf(input, "%d",&count);
count < MIN || count > MAX ? exit(2) : count
}
..那不行!我知道我可以使用上面的语句返回2个值(在开始时使用 return
关键字,但如果我想要这样的话怎么办?int <$ c $会发生什么c> count 当我在第二个函数中使用我的false语句时我无法将值返回给main函数?
...and that won't work! I know that I can return 2 values with the above statement (using return
keyword at the start but what if I want to something like that? What happens to int count
when i use my false-statement in the second function and I can't return the value to main function?
推荐答案
不,它不会有两个原因:
1)退出函数不返回一个值(它是一个void
函数: http://www.cplusplus.com/reference/cstdlib/exit/ [ ^ ])和?:运算符需要两侧的相同类型的值:
2)该函数没有return
声明!
即使你可以,这也是一个坏主意。仅仅因为你 可以 做某事并不意味着你应该做。我 可以 在高速公路/州际公路上行驶错误 - 但这将是一件愚蠢的事情!
那段代码 - 即使它确实有用 - 也不是更清晰 - 更难阅读和理解。
试试这样:
No, it won't work for two reasons:
1) The exit function does not return a value (it's avoid
function: http://www.cplusplus.com/reference/cstdlib/exit/[^]) and the ?: operator requires a value of the same type on both sides of the ":"
2) The function does not have areturn
statement!
Even if you could, it's a bad idea. Just because you can do something doesn't mean you should. I could drive the wrong way up the motorway / interstate - but it would be a stupid thing to do!
That code - even if it did work - isn't tidier of clearer - it's harder to read and understand.
Try like this:
int count_numbers(FILE *input) {
int count = 0;
fscanf(input, "%d",&count);
if(count < 1 || count > 30) exit(2);
return count;
}
这篇关于从C中的int函数返回一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文