无符号函数必须返回一些东西吗?? [英] Do unsigned functions has to return something??

查看:27
本文介绍了无符号函数必须返回一些东西吗??的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我正在做一个练习,我必须用 C 编写一个无符号函数,我有一个问题,我是否必须因为函数的类型而返回一些东西??还是可选的??

Hey I'm working on an exercise where I have to program an unsigned function in C, and I have a question, do I have to return something because of the type of the function?? Or is it optional??

推荐答案

在正常使用中,任何声明返回值的函数都应该返回一个值.这在很大程度上取决于良好的编程习惯.未能返回值通常是错误的征兆.但是,这不是 C 标准所要求的,有两个例外.

In normal use, any function declared to return a value ought to return a value. This is largely a matter of good programming practice. Failing to return a value is often a sign of an error. However, this is not required by the C standard, and there are two exceptions.

C 2018 6.9.1 12 允许函数通过到达其代码的末尾而不返回值来终止,前提是调用者不使用函数的值:

C 2018 6.9.1 12 allows a function to terminate by reaching the end of its code without returning a value, provided the caller does not use the value of the function:

除非另有说明,如果到达终止函数的},并且调用者使用了函数调用的值,则行为未定义.

Unless otherwise specified, if the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.

函数在某些情况下可能返回值而不在其他情况下返回值的一种情况是,它被设计为根据命令执行各种不同的操作.例如:

One case where a function might return a value in some situations and not in others is where it is designed to perform various different actions upon command. For example:

unsigned DoSomething(int command, int parameters[])
{
    switch (command)
    {
        case GetSomething:
            …
            return Something;
        case RememberSomething;
            Something = parameters[0];
            …
            break;
    }
}

此类设计可能容易出错,应慎重考虑.由于函数被声明为返回一个值,程序员可能会期望它这样做,并在没有返回值的情况下无意中将函数的值分配给另一个对象,从而导致未定义的行为.

Such designs may be error-prone and ought to be considered carefully. Since the function is declared to return a value, a programmer might expect it to do so and inadvertently assign the value of the function to another object in a situation where no value is returned, resulting in undefined behavior.

此外,一个函数可能根本不返回,并且有一个函数说明符用于明确地告诉编译器是这样,_Noreturn,如 6.7.4 中所指定.此行为通常仅用于异常情况.例如,标准函数abortexit 终止程序,因此它们不会返回.当然,它们是用 void 声明的,所以它们从不返回任何东西.但是,您可能有一个函数在某些情况下调用 exit 而在其他情况下返回一个整数.

Additionally, a function may not return at all, and there is a function specifier for explicitly telling the compiler this is so, _Noreturn, as specified in 6.7.4. This behavior is typically used only in abnormal situations. For example, the standard functions abort and exit terminate the program, so they do not return. Of course, they are declared with void, so they never return anything. However, you might have a function that calls exit in some circumstances and returns an integer in others.

这篇关于无符号函数必须返回一些东西吗??的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆