1

I came across some syntax in C that I am unfamiliar with. After declaring a variable, long ja, the variable was then assigned to using ja=(long)(3.14).

long ja;
ja=(long)(3.14);

What is the significance of having (long), or (variable type) in the assignment to a variable that has already been declared?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
self.username
  • 103
  • 2
  • 6
  • 3
    It's a [cast](http://www.tutorialspoint.com/cprogramming/c_type_casting.htm) from one type to another. – i_am_jorf Jan 04 '16 at 21:35
  • 1
    C11 draft standard n1570, `6. Language 6.5 Expressions 6.5.4 Cast operators`. I suspect there's a lot of the language you are not familiar with. This part is not exactly obscure. – EOF Jan 04 '16 at 21:36
  • `long ja;` both declares and defines the variable. – librik Jan 04 '16 at 22:01
  • 1
    It's a bad way of writing `ja = 3;` or `ja = 3L;`. – Jonathan Leffler Jan 05 '16 at 07:46
  • Possible duplicate of [In C, why are there parentheses around (int) in this example?](https://stackoverflow.com/questions/30790649/in-c-why-are-there-parentheses-around-int-in-this-example) – phuclv Sep 25 '18 at 01:57

2 Answers2

7

This line is an assignment, not a declaration:

ja=(long)(3.14);

It takes 3.14, which is a constant of type double, casts it to long (resulting in the value 3), and assigns that value to ja.

dbush
  • 205,898
  • 23
  • 218
  • 273
3

The value 3.14 is a literal float, and ja is a long
Attempting to assign the floating value to a long lvalue would result in a compiler warning, such as:

warning: implicit conversion turns literal floating-point number into integer:double to long.

To facilitate the assignment properly, and to suppress the warning, the syntax

ja=(long)(3.14)

is said to typecast 3.14 to long.
Typecasting is a way to make a variable of one type, such as a float, act like another type, such as a long, for one single operation.

ryyker
  • 22,849
  • 3
  • 43
  • 87