0
decimal d = 2;
int i = (int) d;

I've seen this several times in which parentheses are wrapped around data types.

Why not just use int i = int d;?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
gzaw
  • 125
  • 1
  • 6
  • 3
    This is the syntax for [type casting](http://www.tutorialspoint.com/cprogramming/c_type_casting.htm). – PM 77-1 Jun 11 '15 at 20:21
  • 1
    it is a cast of the variable `d`, which is defined as a `decimal` to a type of `int` in order to allow the assignment of `d` to `i` to not generate a compiler warning. Usually it is not a good practice and can lead to mysterious bugs. – Richard Chambers Jun 11 '15 at 20:21
  • We don't know what `decimal` is, but we do know that you can initialize a `decimal` with the value `2`. Given that information, the cast is unnecessary; `int i = d;` would perform the conversion implicitly. It might make sense to make it explicit if the cast is non-trivial. What is `decimal`? – Keith Thompson Jul 04 '20 at 03:40

3 Answers3

5

The usage of (int) is called casting (or, type-casting). It is essentially telling that, interpret convert the value of d as to an int (integer) and store it into i.

In other words, it is a way of converting a type to another one (subject to validity of the conversion).

BTW, int i = int d;, as is, is not a valid statement.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • What did I miss? I mean, reason for downvote, anyone? – Sourav Ghosh Jun 11 '15 at 20:25
  • 1
    NMDV, but perhaps "interpret" may not be as good as "convert". – chux - Reinstate Monica Jun 12 '15 at 00:33
  • @chux Thank you for your comment sir. I intentionally used _interpret_ as I did not want anybody to get the misconception that somehow `d`'s value is getting affected. I always have trouble expressing my thoughts in prefect English. Do you suggest I should change that to _convert_ ? – Sourav Ghosh Jun 12 '15 at 06:35
  • Do not recommend changing an answer based on an anonymous down-voter whose intention is not clearly understood. I suggested "convert" as that matches the C spec: "... result from a cast operation (an _explicit_ conversion)." C11 6.3 1 – chux - Reinstate Monica Jun 12 '15 at 13:01
  • @chux Absolutely sir, you're very right. We should abide by the standard and standard only. I was not worrying about the downvoter, anyway, I was bothered about making the answer correct. As per your suggestion, I'll change it to `convert`, as that is what backed by the standard. :-) – Sourav Ghosh Jun 12 '15 at 13:40
0

You're casting d to type int from type decimal. This happens in other languages as well that use static typing.

sulimmesh
  • 693
  • 1
  • 6
  • 23
0

It is a way of converting data type from one type to another using cast operator, usage is as follows:

  • (result data type) expression to be converted
Tlacenka
  • 520
  • 9
  • 15