How to use float?

Oct 28, 2008 at 12:52pm
I want to declare a variable with a float.
Do i have to write a f after the value?

For example:
float wert = 25.56f

But this is correct, too:
1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;

void main ()
{
    float value = 25;
    cout << value;
    system("PAUSE");
}


So, when is it necessary to write a f after the value of a float?

Thank you.
Oct 28, 2008 at 12:56pm
The f after a number is used to say that it is float.
If you don't it will be used as different type but you could assign to a float variable by casting it.
(A number is also automatically converetd)

example of numeric types
1
2
3
4
5
25     //int
25l    //long
25u   //unsigned
25.0  //double
25.0f //float  
Last edited on Oct 28, 2008 at 12:58pm
Oct 28, 2008 at 1:46pm
I have seen a f after the value of a folat.
But I have never used or seen a character after the variable long or unsigned.
I have used it like:
unsigned int = 25;
and
there is no problem with it.
Oct 28, 2008 at 2:52pm
Suppose you have
1
2
3
4
5
6
7
8
9
class C
{
  public:
    char* operator[](unsigned int x) { ... }
    operator char*() { ... }
};
...
C o;
o[5];

What is called, operator[] or operator char* and the built-in operator[]? The former requires the conversion of an int to an unsigned int, the latter requires an user-defined conversion, so the former should be called. But if ptrdiff_t actually is an int, then the latter has a better match for the built-in operator[] on pointers. Due to the fact that the *this pointer participates, even though hidden, in overload resolution, this is an ambiguity! (Which doesn't exist on systems where ptrdiff_t is a long, there the code will work and call operator[]; but since ptrdiff_t is implementation-defined, the code above is non-portable).
So long story short, it may have worked in all your examples, but that doesn't mean that you should rely on automatic conversions if you don't know them very well (as the example should have shown).
Topic archived. No new replies allowed.