I was reading about casts in c++ and got confused about how are the expressions actually evaluated. Consider the following code in which var
is of type int
and after the expression var = (var*10)/10
the memory of var
gets overflowed:
#include<iostream.h>
void main()
{
int var = 25000; // signerd int varies from -32768 to 32767
var = (var*10)/10; // seems like (var*10) is stored in the memory allocated `var`
cout << "Incorrect value of var is:" << var << endl;
var = (long(var)*10)/10;
cout << "correct value of var is:" << var << endl;
}
The incorrect value shown is -1214 and the correct is, as expected, 25000. I am very much confused about how is the expressions var = (var*10)/10;
actually evaluated. Does the compiler evaluates the expression step by step such that the result of first operation[ (var*10) ] performed on the numeric value of var
is stored in it's allocated memory then the value stored in that memory space is used for further operations to be performed.
My knee jerk was that the compiler directly computes the value (var*10) then divides this value with 10 but this doesn't seem to be the case.
So the question is,
- How are expressions, in general and for my specific example, evaluated in C++?
P.S: I know that I am using an outdated dialect of C++ language and C++ compiler.
<iostream.h>
andvoid main
on this occasion, as you've admitted to complicity already ;)int
is usually four bytes now (though not always — the C++ language doesn't fully mandate it so it's up to your platform and toolchain).