Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About letter f (float type) in C/C++

Tags:

c++

c

I am new to C/C++ programming, and i don't know why they put the letter 'f' in the end of a number when assign, like this:

#include <stdio.h>
int main() 
{
    float my_float = 2.34f;
    double my_double = 2.34;
}

I search for a while and i think that if i don't put this letter 'f', the variable my_float will be a double. am I right? I find some way to find how memory use by a variable/ or type of it (in this case this is my_float) but i don't get it, someone can help me?

like image 945
Lê Huy Việt Avatar asked Oct 20 '17 13:10

Lê Huy Việt


2 Answers

In this case they don't need to.

2.34f is a literal of type float (i.e. the other way round than you think judging by your question). Compare 2.34 which is a literal of type double.

In more detail, if you had written float my_float = 2.34; then the compiler would have performed the conversion for you implicitly.

Occasionally you do need to specify the literal explicitly. In C++, for example, consider

void foo(const double&){
    // reformat hard disk
}

void foo(const float&){
    // pay me a bonus
}

int main()
{
    foo(2.34f);
}

Here, we are forcing the appropriate overload of foo to be called.

like image 94
Bathsheba Avatar answered Nov 18 '22 03:11

Bathsheba


The short answer is: for a numerical literal with a decimal point, a suffix of f or F will tell the compiler your numerical literal should be taken as a float number, instead of as a double; it will be taken as a long double if the suffix is l or L. In most systems floats have half the size in memory bytes, and therefore much less precision, than a double number.

This suffix comes from the good old C (although I don't know if it was used before in earlier languages). I recommend you to have a look at the best book about C, The C Programming Language, by Kernighan and Ritchie. In particular, from this book:

Image from 'The C Programming Language, 2nd. Ed., Kernighan & Ritchie

like image 30
J C Gonzalez Avatar answered Nov 18 '22 05:11

J C Gonzalez