Reputation: 29
This shoud return result 21.5 but this return 21 where is mistake please help me.
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
float Funkcja(int a)
{
static_cast<float>(a);
a += 1.5;
return a;
}
void main()
{
float(*pWskazn)(int);
pWskazn = &Funkcja;
cout << (pWskazn)(20);
getch();
}
Upvotes: 0
Views: 158
Reputation: 5239
static_cast<float>(a);
does not make a
a float. It only makes a
as a float at that line when it is interpreted.
float b = static_cast<float>(a);
b += 1.5;
return b;
Upvotes: 1
Reputation: 727037
You are assigning the result back to a
, which is int
. The result of the cast is not used.
Here is how you can fix the function:
float Funkcja(int a)
{
return static_cast<float>(a) + 1.5;
}
A cast is an expression, not a declaration. When you do static_cast<float>(a)
, the compiler calculates the value of the cast, which you can use in further calculations, but the variable itself remains unchanged.
Upvotes: 2
Reputation: 76498
static_cast<float>(a)
does not change the type of a
to float. It converts the value that a
holds to a float. As used in the code snippet it then discards the value because it isn't used.
static_cast<float>(a) + 1.5
will do what you want.
Upvotes: 1
Reputation: 5532
Your cast has no effect, you need to store it in a variable.
float Funkcja(int a)
{
float f = static_cast<float>(a);
f += 1.5;
return f;
}
Upvotes: 6