Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is void returning a value?

Tags:

c++

void

I can't understand one weird thing. Here is my program :

#include <iostream>
using namespace std;

void Swap(int *a , int *b)
{
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}

int main()
{
    int a=0;
    int b=0;

    cout<<"Please enter integer A: ";
    cin>>a;

    cout<<"Please enter integer B: ";
    cin>>b;

    cout<<endl;

    cout<<"************Before Swap************\n";
    cout<<"Value of A ="<<a<<endl;
    cout<<"Value of B ="<<b<<endl;

    Swap (&a , &b);

    cout<<endl;

    cout<<"************After Swap*************\n";
    cout<<"Value of A ="<<a<<endl;
    cout<<"Value of B ="<<b<<endl;

    return 0;
}

Now if you look at the function "Swap", I have used "void Swap". Therefore it must not return any value to main function (only "int" returns a value (at least that's what my teacher has taught me)). But if you execute it, the values are swaped in main function! How come ? Can anyone tell me how its possible ?

like image 639
Silver Falcon Avatar asked Nov 17 '13 12:11

Silver Falcon


People also ask

Do void functions return values?

Void functions are created and used just like value-returning functions except they do not return a value after the function executes. In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value.

What do voids return?

When used as a function return type, the void keyword specifies that the function doesn't return a value. When used for a function's parameter list, void specifies that the function takes no parameters. When used in the declaration of a pointer, void specifies that the pointer is "universal."

Why void is return type?

The void type, in several programming languages derived from C and Algol68, is the return type of a function that returns normally, but does not provide a result value to its caller. Usually such functions are called for their side effects, such as performing some task or writing to their output parameters.

What does void represent in a return statement?

In computer programming, when void is used as a function return type, it indicates that the function does not return a value.


1 Answers

Swap function in your example just swaps two integers, but does NOT return anything.

In order to check what function has retuned, you have to assign it to some variable, like this

int a = swap(&a, &b);

but this piece of code has an error because swap function doesn't return anything.

Another example:

int func() {
    return 18;
}

int main() {
    int a =  func();
    cout << a;
}

Is fine, cause variable a is int and function func returns an int.

like image 66
Dima Avatar answered Sep 18 '22 09:09

Dima