Okay so first is I am confused with the void function. It is said that void function does not return a value. If for example I have a void function that gets user input, like price and month, how do I use price and month to do another function?

int main()
{
    int price;
    int month;
    float discount;

    getUserInput(price, month);

    //how to get discount

    return 0;
}

void getUserInput(int price, int month)
{
    cout << "price: ";
    cin  >> price;

    cout << "month: ";
    cin  >> month
}

float getDiscount (int price, int month)
{
    float discount;

    if(month > 5)
    {
        discount = price * 0.05
    }
    //code goes here
}

Recommended Answers

All 6 Replies

A getUserInput function simply can not be sensibly defined with that signature. It either has to return something other than void or it has to take its parameters by reference (or pointer), so that it can change them.

You could do it by:
1. declaring the variables as global.
2. pass the variables by reference.

use 'out' parameter

There's no such thing in C++.

Oh, my bad. too used to c#, Edited the post. Sorry.

A function can return a value, for example:
int addOne(int a) {return a+1;}
and be used like:
b = addOne(b);

Also it can not return a value, for example:
void addOne(int& a) {a = a+1;}
and be used like:
addOne(b);

In this case, you have both alternatives and you can choose between them depending your personal taste, the clarity, etc.

Exists other functions that never need to return nothing like:
void printLine(int n) {while(n-->0) std::cout '-'; std::cout << std::endl;}
and be used like:
printLine(20);
to write a Line of 20 - : --------------------.

Like this?

void getUserInput(int& price, int& month)
{
    cout << "price: ";
    cin  >> price;
    cout << "month: ";
    cin  >> month
}
float getDiscount (int& price, int& month)
{
    float discount;
    if(month > 5)
    {
        discount = price * 0.05
    }
    //code goes here
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.