question, about implicit conversions

M

Mason Verger

Given:



int center = 0;

int range = 5;

int lower = 0;

What does this statement do? Is range converted to a float then divided by 2
then casted back to int?

center = ((range)/2) + lower;
 
M

Martin Ambuhl

Mason said:
Given:
int center = 0;
int range = 5;
int lower = 0;

What does this statement do? Is range converted to a float then divided by 2
then casted back to int?

No. range is an int, 2 is an int, so range/2 does integer division.
center = ((range)/2) + lower;
range = 5
range/2 = 5/2 = 2
lower = 0
(range/2) + lower = 2 + 0 = 2
center = 2

But with either of the following (or many other similar forms)
(range/2.) + lower
((double)range/2) + lower
the RHS is 2.5, and the assignment to an int now drops the fractional part.
center becomes 2 in this case as well.
 
M

Mike Wahler

Mason Verger said:
Given:



int center = 0;

int range = 5;

int lower = 0;

What does this statement do?

center = ((range)/2) + lower;
Is range converted to a float
No.

then divided by 2

It's divided by two using 'integer division', which
will truncate any remainder. I.e. range / 2 will
give a result of 2.
then casted back to int?

No conversions or casts are performed in your example.
All your operands already have the same type.


-Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top