3

What is a safer method to perform division:

long long / int or long long / (long long) int?

On dividing a long long by an int, can there be some security issues or any logical issues?

xennygrimmato
  • 2,646
  • 7
  • 25
  • 47

2 Answers2

4

On dividing a long long by an int, can there be some security issues or any logical issues?

The answer is NO with a condition that your denominator is not 0.

From the docs:

Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:

  • If either operand is of type long double, the other shall be converted to long double.
  • Otherwise, if either operand is double, the other shall be converted to double.
  • Otherwise, if either operand is float, the other shall be converted to float.
  • Otherwise, the integral promotions (4.5) shall be performed on both operands.
  • Then, if either operand is unsigned long the other shall be converted to unsigned long.
  • Otherwise, if one operand is a long int and the other unsigned int, then if a long int can represent all the values of an unsigned int, the unsigned int shall be converted to a long int; otherwise both operands shall be converted to unsigned long int.
  • Otherwise, if either operand is long, the other shall be converted to long.
  • Otherwise, if either operand is unsigned, the other shall be converted to unsigned.

[Note: otherwise, the only remaining case is that both operands are int]

So it would be like

int / int => returns int

float / float => returns float

double /double => returns double

int / double => returns double

int / float => returns float
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

As has already been said, going up the scale from lower to higher precision (e.g. float to double to long double, there is no problem with conversions) —each higher one in the list can hold all the values of the lower ones, so the conversion occurs with no loss of information.

For integral promotions (e.g long int and int)

If either operand is a long int, then the other one is converted to long int, and that is the type of the result.

So, this is safe (except divide by zero, of course). For more details.

Novak007
  • 426
  • 1
  • 9
  • 23