I recently saw this at the top of one of my assembly files and realised I had spent ages using it in the process of printing integers without actually realising where it came from originally (used in my basic assembly template) or what the 10, 0 on the end means:
section .data
intfmt: db "%d", 10, 0
Could anyone break this down and explain the different components, specifically of line 2?
I am now trying to read input using scanf and it seems this format isn't working correctly for this. Think it's about time I learned what the numbers meant!
Also, if you have any ideas about reading in input on a 64bit architecture using scanf, I haven't done it before and it's causing me some problems so any pointers to doing that would also be appreciated!
intfmt:
is a label -- it could be any string, but other code refers to it.db
is the "define bytes" pseudo-instruction. Instead of assembling a machine code instruction, it dumps raw bytes into the code stream (.data section in this case)."%d", 10, 0
are the bytes to dump into the stream. The first is an ascii string, which dumps two bytes (the characters '%' and 'd'),10
is a newline character (\n
in C), and 0 is a null byte.Note that the string is a raw string -- NOT nul terminated, and NOT supporting any C style escapes (like
\n
for newline). So overall this creates something equivalent to the C string "%d\n" with a newline and a NUL terminator.Now as to why this works for printf and not for scanf (and why that switches if you remove the 10) has to do with how printf and scanf work and what a newline means to each.
In printf, the newline prints a newline and then (if the output is in line buffered mode, which it probably is), flushes the internal output buffer so you can actually see the result. So when you remove the 10, there's no flush and you don't see the output.
In scanf, the newline means "read and throw away character until you reach a NON-whitespace character", leaving that character as the next to be read. So if you're doing scanf on a terminal input (for example), the newline will cause it to block until you enter a non-blank line after the number...