Home > Software engineering >  Why does this example use `2.` instead of `2.0` (decimal point with no decimals)?
Why does this example use `2.` instead of `2.0` (decimal point with no decimals)?

Time:02-05

I came across this tutorial, and I've never encountered this syntax: gp_Pnt aPnt1(-myWidth / 2., 0, 0);. I'm likely looking in the wrong places, but why does G accept all 3 of these variable initializations?

double a = 2;
double b = 2.;
double c = 2.0;

I don't remember coming across 2. - is this shorthand for 2.0, or are they different?

CodePudding user response:

2 is an int literal.

2. and 2.0 are identical and are double literals. The first one is just a shorter version.

2.f and 2.0f are identical and are float literals.

CodePudding user response:

According to this documentation, there are six ways to declare a floating-point literal in c . Three of which use decimal format, while the other three uses hex format. As for the decimal format, here're the syntaxes:

digit-sequence decimal-exponent suffix(optional) (1)

digit-sequence . decimal-exponent(optional) suffix(optional) (2)

digit-sequence(optional) . digit-sequence decimal-exponent(optional) suffix(optional) (3)

So the literal 2 in double a = 2;uses syntax (1). The literal 2. in double b = 2.; uses syntax (2). The literal 2.0 in double c = 2.0 uses syntax 2.0. As far as I know, there are no difference in semantics in this context. However, in another context, for example, int d = 2;, the literal 2 stands for an integer literal and not floating point literal.

  • Related