سؤال

I do not see how adding something like L to a number makes a difference. For example if I took the number 23.54 and made it 23.54L what difference does that actually make and when should I use the L and not use the L or other add ons like that? Doesn't objective-c already know 23.54 is a long so why would I make it 23.54L in any case?

If someone could explain that'd be great thanks!

هل كانت مفيدة؟

المحلول

Actually, when a number has a decimal point like 23.54 the default interpretation is that it's a double, and it's encoded as a 64-bit floating point number. If you put an f at the end 23.54f, then it's encoded as a 32-bit floating pointer number. Putting an L at the end declares that the number is a long double, which is encoded as a 128-bit floating point number.

In most cases, you don't need to add a suffix to a number because the compiler will determine the correct size based on context. For example, in the line

float x = 23.54;

the compiler will interpret 23.54 as a 64-bit double, but in the process of assigning that number to x, the compiler will automatically demote the number to a 32-bit float.

Here's some code to play around with

NSLog( @"%lu %lu %lu", sizeof(typeof(25.43f)), sizeof(typeof(25.43)), sizeof(typeof(25.43L)) );

int x = 100;
float y = x / 200;  
NSLog( @"%f", y );

y = x / 200.0;    
NSLog( @"%f", y );

The first NSLog displays the number of bytes for the various types of numeric constants. The second NSLog should print 0.000000 since the number 200 is interpreted as in integer, and integer division truncates to an integer. The last NSLog should print 0.500000 since 200.0 is interpreted as a double.

نصائح أخرى

It's a way to force the compiler to treat a constant with a specific type.

23.45 is double, 23.54L is long double, and 23.54f is float.

Use a suffix when you need to specify the type of a constant. Or, create a variable of a specific type: float foo = 23.54;. Most of the time you don't need a suffix.

This is all plain C.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top