Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The <code>sizeof</code> operator doesn't evaluate its argument, it only <a href="https://stackoverflow.com/questions/1995113/strangest-language-feature/2018786#2018786">looks at the type</a> of its operand.</p> <p>Let's say you have an array <code>a</code> with type "array [N] of type T". Then, in most cases, the type of the name <code>a</code> is "pointer to T" (<code>T *</code>), and the value of the pointer is the address of the first element of the array (<code>&amp;a[0]</code>). That is, the name of an array "decays" to a pointer to its first element. The "decaying" doesn't happen in the following cases:</p> <ul> <li>when <code>a</code> is used with the address-of (<code>&amp;</code>) operator,</li> <li>in the initialization of <code>a</code> (it is illegal to assign to arrays in C), and</li> <li>when <code>a</code> is the operand of the <code>sizeof</code> operator.</li> </ul> <p>So, <code>sizeof a</code> gives you <code>N</code> times <code>sizeof(T)</code>.</p> <p>When you do <code>sizeof(a-3)</code>, the type of the operand to <code>sizeof</code> is determined by the expression <code>a-3</code>. Since <code>a</code> in <code>a-3</code> is used in a <a href="https://stackoverflow.com/questions/2035066/type-of-an-array/2035255#2035255">value context</a> (i.e., none of the three contexts above), its type is "pointer to int", and the name <code>a</code> decays to a pointer to <code>a[0]</code>. As such, calculating <code>a-3</code> is undefined behavior, but since <code>sizeof</code> doesn't evaluate its argument, <code>a-3</code> is used only to determine the type of the operand, so the code is OK (see the first link above for more).</p> <p>From the above, <code>sizeof(a-3)</code> is equivalent to <code>sizeof(int *)</code>, which is 4 on your computer.</p> <p>The "conversion" is due to the subtraction operator. You can see a similar, and perhaps more surprising, result with the comma operator:</p> <pre><code>printf("%zu\n", sizeof(1, a)); </code></pre> <p>will also print <code>sizeof(int *)</code>, because of the comma operator resulting in <code>a</code> getting used in a value context.</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