(e-mail address removed) said:
On May 9, 1:34 pm, Richard Heathfield <
[email protected]>
wrote:
(e-mail address removed) said: [...]
#include<stdio.h>
int main()
{
int *p;
p=(int*)10;
printf("%d",(int)p);
}
does this program is in C now..
Well, that's written in C, at least. What is your question about
it? Is it a valid program? Yes, it is. Is it guaranteed to print
10? No, it isn't.
Why is it not guaranteed to print 10??
Because no such guarantee exists. The C Standard says that
converting a pointer to an integer (and vice versa) is possible,
using a suitable cast, but it says nothing about the result except
that it is "implementation-defined".
[...]
Standard says that if an int is converted to int* then result is
implementation defined..
result as in if any read/write is made to that location that may be
implementation defined... as it may not be aligned to page boundary or
a trap representation..
but here no read or write is made to that memory location..
Right, you don't dereference the pointer, but that's not terribly
relevant. The result of the conversion is implementation-defined. It
could even give you a trap representation, which means that the
behavior of just reading the pointer value is undefined (your program
crashing is one of the more benign possible effects).
and moreover first i'm converting it to int* and then printing it back
after converting it back to int..
On many implementations, it's very likely that the program will print
10. But the standard just doesn't make enough guarantees about
integer-to-pointer and pointer-to-integer conversions to ensure that
it will do so.
i can understand this to be implementation defined as..
int *p;
p=(int*)10;
printf("%d",p); //not defined.. i can understand..
Right, because "%d" expects an int, and passing a pointer instead
invokes undefined behavior.
but in the former case i think its valid..
Nope.
--
Keith Thompson (The_Other_Keith) (e-mail address removed) <
http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"