Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The first cast is legal; the second cast may not be legal.</p> <p>The first cast tells the compiler to use the knowledge of the type of the variable to make a conversion to the desired type; the compiler does it, provided that a proper conversion is defined in the language standard.</p> <p>The second cast tells the compiler to forget its knowledge of the variable's type, and re-interpret its internal representation as that of a different type<sup> *</sup>. This has limited applicability: as long as the binary representation matches that of the type pointed by the target pointer, this conversion will work. However, this is not equivalent to the first cast, because in this situation value conversion never takes place.</p> <p>Switching the type of the variable being cast to something with a different representation, say, a <code>float</code>, illustrates this point well: the first conversion produces a correct result, while the second conversion produces garbage:</p> <pre><code>float test = 123456.0f; printf("VALUES:\n"); printf("%f\n", test + 1); printf("%lu\n", (unsigned long)test + 1); printf("%lu\n", *((unsigned long *)&amp;test) + 1); // Undefined behavior </code></pre> <p>This prints</p> <pre><code>123457.000000 123457 1206984705 </code></pre> <p><a href="http://ideone.com/nBgjpL" rel="nofollow noreferrer">(demo)</a></p> <p><hr/> <sup> *</sup> This is valid only when one of the types is a character type and the pointer alignment is valid, type conversion is trivial (i.e. when there is no conversion), when you change qualifiers or signedness, or when you cast to/from a <code>struct</code>/<code>union</code> with the first member being a valid conversion source/target. Otherwise, this leads to undefined behavior. See C 2011 (N1570), 6.5 7, for complete description. Thanks, <a href="https://stackoverflow.com/users/298225/eric-postpischil">Eric Postpischil</a>, for pointing out the situations when the second conversion is defined.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload