Typecasting

M

mail.dsp

Consider following:
unsigned char i= 0;

Now when we perform "++i" Is "i" typecasted into "int", "++" operator
increment its value and finally typecasted into "unsigned char"?


Thanks in advance
 
R

Rolf Magnus

Consider following:
unsigned char i= 0;

Now when we perform "++i" Is "i" typecasted into "int", "++" operator
increment its value and finally typecasted into "unsigned char"?

You mean "converted", not "typecasted". But yes, for all integer arithmetic
operations where all operands are small enough to fit in int, those operands
are converted to int first.
 
J

James Kanze

Consider following:
unsigned char i= 0;
Now when we perform "++i" Is "i" typecasted into "int", "++"
operator increment its value and finally typecasted into
"unsigned char"?

It depends, sort of. First of all, there's no "typecasting"
involved; typecasting is an explicit conversion, and any
conversions here are implicit. But type promotion will occur;
if an int can represent all possible values of unsigned char,
the unsigned char will be promoted to int; otherwise, it will be
promoted to unsigned int. The arithmetic will be performed on
the promoted type, and the results will be converted to the
target type.

For such simple operations, it doesn't matter, but in more
complicated cases, it could.
 
A

Andrey Tarasevich

Consider following:
unsigned char i= 0;

Now when we perform "++i" Is "i" typecasted into "int", "++" operator
increment its value and finally typecasted into "unsigned char"?

Close, but not exactly. '++i' is, by definition, a shorthand for 'i +=
1', which in turn is a shorthand for 'i = i + 1' (aside from some
details irrelevant in this case). The latter expression is evaluated by
promoting 'i' to 'int', calculating 'i + 1' and then converting the
result back to 'unsigned char'.
 
A

Andrey Tarasevich

Andrey said:
Close, but not exactly. '++i' is, by definition, a shorthand for 'i +=
1', which in turn is a shorthand for 'i = i + 1' (aside from some
details irrelevant in this case). The latter expression is evaluated by
promoting 'i' to 'int', calculating 'i + 1' and then converting the
result back to 'unsigned char'.

Also, on a relatively exotic system with the range of 'unsigned char'
exceeding the positive range of 'int', 'i' will get promoted to
'unsigned int' instead of 'int'
 

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,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top