views:

96

answers:

5

What does the letter near the digit constant mean? Just for example:

int number = 0;
float decimal = 2.5f;
number = decimal;

What's difference betweet 2.5f and f2.5 ? I have already looked in manuals, but I really cant understand it. Explaine it me please in a simple format.

+3  A: 

From here:

Floating-point constants default to type double. By using the suffixes f or l (or F or L — the suffix is not case sensitive), the constant can be specified as float or long double, respectively.

I don't thing the format f2.5 is legal.

Otávio Décio
+3  A: 

The value 2.5 would be a double, whereas 2.5f is a float. Unless you have a specific reason not to, it is generally better to use doubles rather than floats - they are more precise and may even be faster.

anon
Can you explain why doubles "may even be faster"?
Cam
James Curran
Why then code shows me "This is: float" but not double?float decimal = 2.5;cout << "This is: " << typeid(decimal).name() << endl;
Molfar
@Molfar 2.5 is a double, `decimal` is a float - storing a double in a float does not change the latter's type, it just loses you information.
anon
@James Curran: that is if you define a modern CPU as x86 specifically. x64 uses SSE2, which doesn't work at 80 bit precision internally.
jalf
@jalf: really? I thought the 80-bit format wasw an IEEE standard. Well, I come here to learn as well as teach....
James Curran
@James: I think 80-bit is a IEEE standard format, yes. But CPU's aren't required to support every IEEE format. Most just support 32 and 64 bit and call it a day, SSE/SSE2 included.
jalf
+2  A: 

What's difference betweet 2.5f and f2.5

  • 2.5f is the value 2.5 as a floating point number,
  • f2.5 is a variable called "f2" followed by ".5" which would be a syntax error.
James Curran
2.5 = 5/2 not 2/5
Potatoswatter
Actually, that was a typo. The slash should have been a decimal point.
James Curran
A: 

f2.5 is illegal. 2.5f (or 2.5F) forces 2.5 to be interpreted as a float, not as double. Relatedly, there's the l/L suffix to make integer constants longs.

number = decimal truncates the latter, I suppose.

delnan
A: 

Purely as additional information (not really a direct answer to the question) I'd note that to specify the type of a character or string literal, you use a prefix (e.g., L"wide string"), whereas with a numeric literal you use a suffix (e.g., 2L or 3.5f).

C++0x adds quite a few more of both prefixes and suffixes to specify more data types (e.g., there are currently only narrow and wide string literals, but C++0x will have narrow, wide, Unicode, raw, and probably at least a couple more I can't think of at the moment). It also adds user-defined literals that let you define your own suffixes, so something like 150km could be used to create a distance object, or "127.0.0.1"ip to create an IP_address object.

Jerry Coffin