0

I am new to Assembly and have been trying to write a program to read a float, store it and then print it, the problem is when I print it with %f flag it prints 0.0 although the scan flag is also %f and the type is .float

.section .data        # memory variables
format: .asciz "%f"    # string terminated by 0 that will be used for scanf parameter
n: .float 0.0             # the variable n which we will get from user using scanf and will be printed by printf

.section .text        # instructions
.globl _main          # make _main accessible from external
_main:                # the label indicating the start of the program
   pushl $n           # push to stack the second parameter to scanf (the address of the integer variable n) the char "l" in pushl means 32-bits address
   pushl $format       # push to stack the first parameter to scanf
   call _scanf        # call scanf, it will use the two parameters on the top of the stack in the reverse order
   add $8, %esp       # pop the above two parameters from the stack (the esp register keeps track of the stack top, 8=2*4 bytes popped as param was 4 bytes)

   pushl n
   pushl $format
   call _printf
   add $8, %esp
   ret

Can someone tell me what is the problem here? Thanks!

Ammar
  • 1
  • 2
    Have you promoted the `float` to the `double` that the variatic function `printf` will be expecting? It doesn't print a `float` even though you used `"%f"`. Although `scanf` and `printf` bear some similarities, there are significant differences. There would be a similar problem if you wanted to output a 1-byte `char` with `%c`: the `printf` will expect an `int` size value, again due to "type promotions". – Weather Vane Jan 06 '22 at 00:06
  • Typo: variatic ==> variadic. Please see [Why does printf() promote a float to a double?](https://stackoverflow.com/questions/28097564/why-does-printf-promote-a-float-to-a-double) Although it's the compiler that generates code to promote it, not `printf` which is an interpretive function and believes it was passed what the C spec tells it to expect. – Weather Vane Jan 06 '22 at 00:23
  • Ok I have tried changing `n` to `.double 0.0` but still the same problem so I might need some clarifications: – Ammar Jan 06 '22 at 11:34
  • - Will `pushl $n` change to `push` as we have changed n from float which is 4 bytes into double which is 8, also in `add $8, %esp` will it change to `add $12, %esp`? Thanks – Ammar Jan 06 '22 at 11:36
  • You can't `push` 8 bytes in 32 bit mode with a single `push` you will need two. If you change `n` to `double` you will also need to change the `scanf` format string. – Jester Jan 06 '22 at 11:47
  • 1
    Ok, now it's working thanks! – Ammar Jan 06 '22 at 12:40
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Jan 14 '22 at 20:37

0 Answers0