Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

confusion about void and what it means.

Tags:

c++

I am very new to programming and am confused about what void does, I know that when you put void in front of a function it means that "it returns nothing" but if the function returns nothing then what is the point of writing the function?? Anyway, I got this question on my homework and am trying to answer it but need some help with the general concept along with it. any help would be great, and please try to avoid technical lingo, I'm a serious newb here.

What does this function accomplish?

void add2numbers(double a, double b) 
    { 
       double sum; 
       sum = a + b; 
    }
like image 601
user1408594 Avatar asked May 21 '12 18:05

user1408594


4 Answers

void ReturnsNothing() 
{
     cout << "Hello!";
}

As you can see, this function returns nothing, but that doesn't mean the function does nothing.

A function is nothing more than a refactoring of the code to put commonly-used routines together. If I'm printing "Hello" often, I put the code that prints "Hello" in a function. If I'm calculating the sum of two numbers, I'll put the code to do that and return the result in a function. It's all about what you want.

like image 79
Mahmoud Al-Qudsi Avatar answered Nov 11 '22 20:11

Mahmoud Al-Qudsi


There are loads of reasons to have void functions, some of these are having 'non pure' side effects:

int i=9;
void f() {
    ++i;
}

In this case i could be global or a class data member.

The other is observable effects

void f() {
    std::cout <<"hello world" << std::endl;
}

A void function may act on a reference or pointer value.

void f(int& i) {
   ++i;
}

It could also throw, although don't do this for flow control.

void f() {
   while(is_not_broke()) {
        //...
   }
   throw std::exception(); //it broke
}
like image 39
111111 Avatar answered Nov 11 '22 22:11

111111


The purpose of a void function is to achieve a side effect (e.g., modify a reference parameter or a global variable, perform system calls such as I/O, etc.), not return a value.

like image 26
Fred Larson Avatar answered Nov 11 '22 20:11

Fred Larson


The use of the term function in the context of C/C++ is rather confusing, because it disagrees wiht the mathematical concept of a function as "something returning a value". What C/C++ calls functions returning void corresponds to the concept of a procedure in other languages.

The major difference between a function and a procedure is that a function call is an expression, while a procedure call is a statement While functions are invoked for their return value, procedures are invoked for their side effects (such as producing output, changing state, and so on).

like image 28
Sergey Kalinichenko Avatar answered Nov 11 '22 21:11

Sergey Kalinichenko