user3505910
user3505910

Reputation: 1

how does a function return value work

E.g 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. e.g

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

Upvotes: 0

Views: 68

Answers (3)

Dr. Debasish Jana
Dr. Debasish Jana

Reputation: 7118

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.

Upvotes: 0

James Kanze
James Kanze

Reputation: 153899

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.

Upvotes: 1

Maroun
Maroun

Reputation: 95948

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..

Upvotes: 1

Related Questions