Re: Code problem
On 2012-06-08, Keith Thompson <kst-u@mib.org> wrote:
> Angel <angel+news@spamcop.net> writes:
>> On 2012-06-08, rage <hansum.rahul@gmail.com> wrote:
>>> Can someone please help me out on this?
>>>
>>> #include<stdio.h>
>>> main()
>>> {
>>> int i;
>>> int *j=10;
>>
>> In this line, you're converting an integer value to a pointer. That
>> is an operation with undefined behavior. (Except if the integer is a
>> constant value of zero, if I recall right.)
>
> What makes you think there's a conversion there?
>
> The declaration violates a constraint. An initialization has
> the same constraints as a simple assignment (N1570 6.7.9p11).
> The rules for simple assignment say that if the left hand side has
> pointer type, the right hand side must have pointer type (either
> a compatible type or void*) or it can be a null pointer constant.
>
> Since
>
> int *j = 10;
>
> doesn't satisfy these constraints, there is no definition of its
> behavior. In particular, the standard does not say or imply that the
> int value 10 should be converted to int*.
>
> That was the typical behavior for pre-standard versions of C, and
> most compilers that don't reject the declaration will generate code
> equivalent to:
>
> int *j = (int*)10;
>
> But it's not required.
>
> Note that the behavior of an integer-to-pointer conversion is not
> (entirely) undefined. N1570 6.3.2.3 says:
>
> An integer may be converted to any pointer type. Except as
> previously specified, the result is implementation-defined,
> might not be correctly aligned, might not point to an entity
> of the referenced type, and might be a trap representation.
>
> with a footnote:
>
> The mapping functions for converting a pointer to an integer
> or an integer to a pointer are intended to be consistent with
> the addressing structure of the execution environment.
>
> (But that's not relevant to this code because, as I said, no conversion
> is implied.)
Haha, thanks for clarifying and correcting. Clearly I've been out of C
programming so much that what I know no longer matches with current
standards. I suppose I should go brush up my skills. :-)
Anyway, the bottom line to the original poster is "don't mix up integers
and pointers unless you really know what you're doing", yes?
--
"C provides a programmer with more than enough rope to hang himself.
C++ provides a firing squad, blindfold and last cigarette."
- seen in comp.lang.c
|