简体   繁体   中英

how does a function return value work

Eg function:

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

This function has return type int. Why we can write this function in Main without assign anything. 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++; you're allowed to ignore the return value.

At the implementation level: int is usually returned in a register; 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. 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. That does not necessary mean this is equivalent to void return type. You have the option of checking the return value, but you don't need to check that, upto you, optional. Hope that answers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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