Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct datatype for a variable

Tags:

c

I have a question like this: Which of the following is the correct datatype for the variable like this:

a = 23.5

a) float
b) double
c) long double
d) None

According to me, it should be double. Because, if we

 float a = 23.5

Then, actually, we are initializing a float variable by a double constant. Am I right saying that it is option b?

like image 871
user3797829 Avatar asked Jul 03 '14 07:07

user3797829


2 Answers

It depends on what type you need for a to be in your program logic, not what type of value it's initialized.

Yes, float a = 23.5;, there is a conversion from the double literal 23.5 to the float variable a, but it's fine. For instance, to initialize a double variable to 42.0, people usually use

double a = 42;

in which 42 is of type int, instead of the longer

double a = 42.0;

So in my opinion, float, double, or long double can all be considered correct here.

like image 77
Yu Hao Avatar answered Sep 30 '22 10:09

Yu Hao


You can declare this variable as double, float, or long double.

The difference is in the range of the type.

For example (one possible way):

float- 4 bytes
double - 8 bytes
long double - 12 bytes

You can see more details here: http://www.lix.polytechnique.fr/~liberti/public/computing/prog/c/C/CONCEPT/data_types.html

like image 24
Asaf Kahlon Avatar answered Sep 30 '22 12:09

Asaf Kahlon