0

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
}
4
Contributors
6
Replies
35
Views
2 Years
Discussion Span
Last Post by redtribal23
0

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.

0

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

Edited by necrovore: Wrong information.

0

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

Edited by Maritimo

0

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
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.