msg: .asciiz “\nHello, World!\n”
li $v0, 4
la $a0, msg
li $v0, 10
How it works
Assembly language is almost pure “machine” code and is a set of very detailed instructions to be run by a specific type of processor. In this example, we use the language for MIPS, a class of processors found in all sorts of electronics, networking equipment, and even game systems like the Playstation 2.
In this code, starting from “main”, we do the following:
- Put the number 4 into register v0.
- Put the address of “msg” into register a0.
- A system-call that does something based on v0 and a0; in this case, “4” meant print, and it looks for what to print using the memory address stored in a0
- The last system call uses the number “10”, which means to exit the program
To actually run this code, we’d need to assemble this code and run it on a MIPS processor. For a “normal” user trying to learn to code assembly, it’s easier to use a simulator such as QtSpim. This is a “virtual” MIPS processor which we can use to run this code:
Why Use Assembly
There’s very little “need” to use assembly for 99.999% of programmers out there. However, assembly lets us give computers very specific instructions — which is usually going to be a lot more efficient and thus faster code. Realistically, assembly would only be used for special parts of programs that are run all the time in a program, and the programmers wants every last drop of speed and efficiency.
Assembler is hard to write, read, and debug; basic tasks take a lot of code as well. It is also the least portable form of coding – that is, you can only run it on the processor it was designed for. The MIPS assembly code above does not work on an x86 processor found in your desktop computer, or on an ARM processor found in your smartphone.