简体   繁体   English

函数返回值如何工作

[英]how does a function return value work

Eg function: 例如功能:

int pr()
{
   std::cout<<"test"<<std::endl;
   return 0; 
}

This function has return type int. 此函数的返回类型为int。 Why we can write this function in Main without assign anything. 为什么我们可以在Main中编写此函数而不指定任何内容。 eg 例如

int main()
{
    int i = pr();  // all right.
    pr();   // but why is this correct also?
    // is this similar void function this moment?
}

It simply executes the function and the return value gets lost, it's not assigned to anywhere, gets ignored. 它只是执行函数而返回值丢失,它没有分配给任何地方,被忽略。

It's allowed because it's not forbidden. 这是允许的,因为它不被禁止。 There might be a situation where you care only about the logic and you don't really want to use the return value which indicates something that's not important for your current task. 可能存在这样一种情况:您只关心逻辑,而您实际上并不想使用返回值来指示对您当前任务不重要的事情。 For example: 例如:

int openFiles(string directory) {
    //opens files on directory and returns the number
    //of files that were successfully opened
}

I might be not interested of the return type.. 我可能对返回类型不感兴趣..

Because the standard says so. 因为标准是这样说的。 In many languages, not using the return value would be an error. 在许多语言中,不使用返回值将是一个错误。 For various historical reasons, this is not the case in C or C++; 由于各种历史原因,在C或C ++中并非如此; you're allowed to ignore the return value. 你被允许忽略返回值。

At the implementation level: int is usually returned in a register; 在实现级别: int通常在寄存器中返回; if you ignore the return value, the compiler doesn't do anything with that register. 如果忽略返回值,编译器不会对该寄存器执行任何操作。 For class types, however, the caller must destruct the returned value, even if he ignores it. 但是,对于类类型,调用者必须销毁返回的值,即使他忽略了它。

In C/C++, a function may choose its return type as void or some specific type. 在C / C ++中,函数可以选择其返回类型为void或某些特定类型。 However, if non-void is the return type of a function, whenever the function is called, the caller may or may not use the return value. 但是,如果non-void是函数的返回类型,则无论何时调用该函数,调用者都可以使用或不使用返回值。 That does not necessary mean this is equivalent to void return type. 这并不意味着这相当于void返回类型。 You have the option of checking the return value, but you don't need to check that, upto you, optional. 您可以选择检查返回值,但是您无需检查,可选。 Hope that answers. 希望得到答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM