0

I have the following code in C:

        int l;
        short s;

        l = 0xdeadbeef;
        s = l;

Assuming int is 32 bits and short is 16 bits, when performing s = l, s will be promoted to 32 bits and after assignment, only lower 16 bits will be kept in s. My question is that when s is promoted to 32 bits, will the additional 16 bits be set to 0x0 or 0xf ?

Source : http://www.phrack.com/issues.html?issue=60&id=10

Jake
  • 16,329
  • 50
  • 126
  • 202

3 Answers3

2

Actually s is not promoted at all. Since s is signed and l is too large to fit in s, assigning l to s in this case is implementation defined behavior.

6.3.1.3-3

Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • @Jake I did. It looks confusing. All that "promotion" / "demotion" of s is unmentioned by the standards - it's an artificial explanation. – cnicutar Mar 09 '12 at 15:58
  • @Jake A Phrack article is always useful. You just have to take it with a bit of salt. – cnicutar Mar 09 '12 at 16:00
0

Assembler have operation for moving whole register or part of it (MOV EAX, 0, MOV AX, 0, MOV AL, 0 - respectively 32bits, 16bits, 8bits). As short is 16-bit integer MOV AX, 0 form would be used, although, that depends on compiler implementation.

Im0rtality
  • 3,463
  • 3
  • 31
  • 41
0

I assume you're going to promote s to some wider type. This depends on the destination type: whether it is signed or unsigned. If the destination type is signed there will be signed promotion done. Otherwise -- unsigned promotion. The signed promotion fills higher bits by 0 or 1 depending on the sign of the promoted value.

Jurlie
  • 1,014
  • 10
  • 27