Note that there are some explanatory texts on larger screens.

plurals
  1. POIs it dangerous to promote types in printf arguments?
    primarykey
    data
    text
    <p>My questions stem from trying to use printf to log things when trying to build for multiple bit-depth platforms (32/64 for example).</p> <p>A problem that keeps rearing its ugly head is trying to print ints on multiple architectures. On 32 bit it would be something like</p> <pre><code>printf(" my int: %d\n", myInt); </code></pre> <p>but on 64 bit, it would have to be changed to </p> <pre><code>print (" my int: %ld\n", (long)myInt); </code></pre> <p>I have two related questions:</p> <ol> <li><p>My first thought was that when you tell printf to print a variable, giving it a format, it would look at the address of that variable and grab as many bytes as it needed for that format. This seemed like a big problem at first. For example if you had a variable myChar that was a char (1 byte), but used a format specifier of %d, that would tell printf to go to the address of myChar and grab the next 4 bytes to treat it like an int. If this were the case, it seems like printf would grab garbage date from neighboring variables (because it was grabbing 4 bytes, but the real value is only 1 byte). This appears to not be the case however. By using myChar and specifying %d, printf grabs 1 byte and then pads the upper 3 bytes with 0's. Is my understanding correct here?</p></li> <li><p>If the above is true, is there any real harm in always promoting variables up to their largest values to avoid the types of problems seen in the 32/64 bit case. For example if you have a short variable myShort, and an int variable, myInt, is there any downside in printing them always as:</p> <p>printf("myShort %ld", (long)myShort); printf("myInt %ld", (long)myInt);</p></li> </ol> <p>Thanks for any clarification.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    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