How to set a pointer as default parameter in C ++?

3

I'm "programming in C" but compiling using the .cpp extension and g ++ to have some facilities. My goal is to do a program that receives a starting salary and calculates the final salary according to a certain bonus. The bonus is given in percentage over the starting salary, and if the function is called without a bonus amount being passed, a value of 15% must be assumed.

What I did:

#include <cstdio>

float calculaSalario(float* salario, float* bonificacao = 15.0f);

int main (void)
{
    float salario = 0;
    float bonificacao = 0;

    scanf("%f", &salario);
    scanf("%f", &bonificacao);

    calculaSalario(&salario, &bonificacao);

    printf("%f\n", salario);

    return 0;
}

float calculaSalario(float* salario, float* bonificacao = 15.0f)
{
    *salario = *salario + *salario * (*bonificacao/100);
}

However, I'm getting the following errors:

  • error: could not convert '1.5e + 1f' from 'float' to 'float *' float calculates Salary (float * salary, float * bonus = 15.0f);

  • (float *, float *) ': error: default argument given for parameter 2 of' float calcula (float *, float *) '[-fpermissive] note: previous specification in' float calculates Salary (float *, float *) 'here float calculates Salary (float * salary, float * bonus = 15.0f);

asked by anonymous 21.08.2018 / 03:15

1 answer

5

The first obvious problem is using float for monetary value, you can not . But by a tremendous misfortune does not generate error, it only causes problems sometimes, and the programmer thinks it's right.

Another error is to use pointer in this function, it does not make sense, mainly because it already foresees to return something. Actually what the function returns is not the salary, so the correct one is neither save in the same variable, it works and it is right, but it is more readable and organized to save in a variable that is the salary subsidized. It is not legal to reuse variable for something else.

#include <cstdio>

float calculaSalario(float salario, float bonificacao = 15.0) { return salario + salario * (bonificacao / 100); }

int main() {
    float salario = 0;
    float bonificacao = 0;
    scanf("%f", &salario);
    scanf("%f", &bonificacao);
    salario = calculaSalario(salario, bonificacao);
    printf("%f\n", salario);
}

See running on ideone . And no Coding Ground . Also put it in GitHub for future reference .

    
21.08.2018 / 03:21