A question About the difference of %hd and %d in scanf() in C

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • yyda
    New Member
    • Aug 2024
    • 3

    A question About the difference of %hd and %d in scanf() in C

    Code:
    	int y;
    	short s;
    
    	scanf("%d %d", &y, &s);
    	printf("%d,%d\n", y, s);
    the output is gonna be"0,short(s) ".
    Obviously the printf() doesn't care %hd or %d,but why y presents "0" instead of s in the case of s received the wrong type and s presents rightly
  • dev7060
    Recognized Expert Contributor
    • Mar 2017
    • 656

    #2
    Code:
            int y;
            short s;
         
            scanf("%d %d", &y, &s);
            printf("%d,%d\n", y, s);
    the output is gonna be"0,short(s) ".
    Obviously the printf() doesn't care %hd or %d,but why y presents "0" instead of s in the case of s received the wrong type and s presents rightly
    short s may or may not alter the bytes occupied by int y (which could be present in adjacent memory locations) and may cause potential corruption. Kind of undefined behavior; the exact outcome depends on the system and compiler. Compilers may pad memory differently or handle misaligned memory accesses in various ways.

    Try inputting a value that doesn't fall within the range of short; this might affect both variables. Additionally, consider storing one on the heap and the other on the stack. Do they both appear correct?

    Comment

    • yyda
      New Member
      • Aug 2024
      • 3

      #3
      Thank you!
      So this is an undefined,r?
      I tried to store y in heap,it works as I expected.Looks like it's about stack.

      Comment

      • dev7060
        Recognized Expert Contributor
        • Mar 2017
        • 656

        #4
        On my machine

        Within short range
        Input: 5 55
        Output: 0 55

        Outside short range
        Input: 5 5555555
        Output: 84 -15005

        y on stack, s on heap
        Input: 5 5555555
        Output: 5 5555555

        Comment

        • yyda
          New Member
          • Aug 2024
          • 3

          #5
          Originally posted by dev7060
          On my machine

          Within short range
          Input: 5 55
          Output: 0 55

          Outside short range
          Input: 5 5555555
          Output: 84 -15005

          y on stack, s on heap
          Input: 5 5555555
          Output: 5 5555555
          Yes!It's the same here.I mean the value is random when out short range.Whether s or y is stored in heap,it works.They may be constant in memory so there is a unexpected interference?

          Comment

          Working...