On May 26, 1:14 am, "osmium" <r124c4u...@comcast.netwrote:
"Shraddha" wrote:
int *s=(int *)2000;
int *p=(int *)1000;
printf("%d",p-s);
You would do well to compile this, run it, see what happens and remeber it.
#include <stdio.h>
int main(void)
{
double x = 1.e35;
int n;
n = (int) x;
printf("%d\n", n);
return 0;
}
You would do well *not* to try to run such a program. It's
undefined behavior, and there is no guarantee with regards as to
what might happen.
Rather than playing around, it would be well to learn the
language. Or even basic principles: I know of know language
where such conversions do anything useful---they're either
undefined behavior, as in C/C++, or they are guaranteed to stop
the program. A good programmer verifies before converting,
always.
The message is clear.
A cast says: "compiler, do this conversion. I am a
smart human and I know what I am doing."
The cast, in this case, changes absolutely nothing, since it is
an implicite conversion. At best, it might shut up a warning,
although for various more or less historical reasons, very few
compilers warn about lossy conversions.
The compiler believes you and does its best to comply.
I'd express it differently: the compiler supposes that you know
what you are doing (cast or not), and that if you are assigning
a double to an int, you have verified that it won't overflow.
So it takes no precautions for such an eventuality.
The results may be nonsense, which is what I get on my
compiler. It prints -250. The compilers I have used say "can
not convert' in the pre-cast error message. It really means:
I *will not*, unless you explicitly tell me to.
What compiler is this? Double to int is a perfectly legal
conversion, and the compiler is required to compile the code.
(Actually, not in this case, because even the simplest optimizer
will immediatly determine that the conversion will overflow, and
that the program will contain undefined behavior, regardless of
the input. But in general, this is not verifiable at compile
time.)
--
James Kanze (Gabi Software) email:
ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34