Does anyone know what wrong with this code, appearantly there is an error but it will output the right answer anyway.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream >
using namespace std;
float* calculatePercentage(float mark , float total)
{
float percentage = mark/total *100;
return &percentage;
}
int main()
{
float* percent = 0;
percent = calculatePercentage (1,10);
cout << "The percentage is " << *percent << "%" << endl;
return 0;
}
You are returning a pointer to a local variable. The percentage variable exists only in the calculatePercentage function. As soon as the function exits, that variable goes out of scope (dies)... meaning the pointer you are returning instantly becomes a bad pointer.


You should not be using pointers at all for this. Instead, just have calculatePercentage return a normal float... and make your percent variable in main a normal float instead of a pointer.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream >

using namespace std;

float calculatePercentage(float mark, float total)
{
  return mark / total * 100;
}

int main()
{
  float percent = calculatePercentage(1,10);
  cout << "The percentage is " << percent << "%" << endl;
  return 0;
}
Topic archived. No new replies allowed.