Chapter 3.1: Programming Languages

Microprocessors
Software and language levelsMachine languageA sample instruction format Assembly languages“Welcome” on different platforms Compiled languagesInterpreted languagesOne program in 14 languages + 8086
Sercan KÜLCÜ · Giresun University · Computer Engineering

Introduction

Learning Outcomes

Language levels

Explain the difference between machine language, assembly language and high-level languages.

Machine code

Encode and decode binary instructions for a given instruction format.

Assembly

Explain how the assembler and linker turn source code into an executable; read short programs that make system calls.

Platform dependence

Explain why the same program is written differently for x86, 68000, ARM, PowerPC and different operating systems.

Compilation and interpretation

Compare compilers, linkers, interpreters and JIT.

Reading across languages

Trace one algorithm in several languages and in 8086 assembly.

Software

Software

  • Software makes the hardware work correctly, in concert and as intended.
  • The operating system
    • is the computer's core software;
    • it manages the hardware and controls how other software runs.
  • Programming languages
    • exist to build software;
    • there are many languages aimed at different fields.
  • The evolution of programming languages mirrors the major advances in computer technology.
User Applicationsbrowser, compiler, game Operating systemsystem calls, drivers HardwareCPU, memory, I/O

Software

Programming Languages: Levels

CompiledC, Rust, Go InterpretedPython, Ruby High-level languages Assembly languageMOV AL, 5 Machine language1011 0000 0000 0101 abstraction increases hardware (processor)
  1. Machine languages: the 0s and 1s the processor runs directly.
  2. Assembly languages: a symbolic (mnemonic) notation for machine instructions.
  3. High-level languages
    • compiled: translated to machine language first, then run;
    • interpreted: processed line by line at run time.
The higher the level, the more portability and readability, and the less direct control over the hardware.

Software · Step by step

One Operation at Three Levels: x = a + b

High level (C)x = a + b;Where the variables live and which registers to use is left to the compiler.
Assembly language (8086)
MOV AX, [a]     ; load a into AX
ADD AX, [b]     ; AX = AX + b
MOV [x], AX     ; store result in x
Each line corresponds to one machine instruction.
Machine language (a = 0200h, b = 0202h, x = 0204h)
A1 00 02        ; MOV AX, [0200h]
03 06 02 02     ; ADD AX, [0202h]
A3 04 02        ; MOV [0204h], AX
Addresses are stored low byte first (little-endian): 0200h → 00 02.

Software · Step through the code

Code Trace: How Does x = a + b Run in Memory?

org 100h
mov ax, [0200h]   ; A1 00 02
add ax, [0202h]   ; 03 06 02 02
mov [0204h], ax   ; A3 04 02
ret               ; C3
code (0100h–010Ah)A1000203060202A30402C3IP = 0100hdata150200ha000201h270202hb000203h??0204hx??0205hAX????FETCH

IP = 0100h. Fetch: A1 00 02 is read. A1 = “load a word from memory into AX”; the address bytes 00 02 → 0200h (little-endian).

code (0100h–010Ah)A1000203060202A30402C3IP = 0103hdata150200ha000201h270202hb000203h??0204hx??0205hAX0015hEXECUTE

Execute: the bytes at 0200h and 0201h are 15 00 → AX = 0015h (a = 21). IP = 0103h.

code (0100h–010Ah)A1000203060202A30402C3IP = 0103hdata150200ha000201h270202hb000203h??0204hx??0205hAX0015hFETCH

Fetch: 03 06 02 02 (4 bytes). 03 = ADD r16, r/m16; ModR/M 06 = “AX, direct address”; address 0202h.

code (0100h–010Ah)A1000203060202A30402C3IP = 0107hdata150200ha000201h270202hb000203h??0204hx??0205hAX003ChEXECUTE

Execute: b = 0027h (39) is read, AX = 15h + 27h = 003Ch (60). IP = 0107h.

code (0100h–010Ah)A1000203060202A30402C3IP = 0107hdata150200ha000201h270202hb000203h??0204hx??0205hAX003ChFETCH

Fetch: A3 04 02: A3 = “store AX to memory”, target address 0204h.

code (0100h–010Ah)A1000203060202A30402C3IP = 010Ahdata150200ha000201h270202hb000203h3C0204hx000205hAX003ChEXECUTE

Execute: AX is written low byte first: 0204h ← 3C, 0205h ← 00. x = 60.

code (0100h–010Ah)A1000203060202A30402C3IP = 010Ahdata150200ha000201h270202hb000203h3C0204hx000205hAX003ChFETCH

C3 = RET. The single C line x = a + b; became 3 instructions, 10 bytes of machine code.

Assumption: a = 0015h (21), b = 0027h (39); the data shares the code segment (COM program).

Machine Language

Machine Languages

  • The lowest-level language, made of 0s and 1s; the only one the processor understands.
  • Entirely processor- and hardware-dependent: machine code written for the 8086 does not run on ARM.
  • ENIAC (1945), one of the first general-purpose electronic computers, was programmed directly in hardware with cables and switches.
  • Today
    • every processor family has its own machine language (instruction set);
    • it is not used directly because it is impractical to read and write.
  • Assembly languages reduce the dependence on machine language and make programming more human-friendly.
8086 · MOV AL, 51011MOV imm0w=0000AL00000101imm = 5= B0 05ARM · MOV r0, #51110 0011 1010 0000 0000 0000 0000 0101= E3A00005 (32 bits)
On the 8086 the bytes B0 05 mean “load 5 into AL”. On ARM the same job is encoded as a completely different 32-bit word.

Machine Language

Designing a Sample Machine Language

o o o o h h k k bit 7bit 0 opcode (4 bits) dest (2 bits) source (2 bits)
OpcodeMeaning
0000HALT: stop the program
0001ADD: addition
0010SUB: subtraction
0011AND: logical AND
0100OR: logical OR
  • Instructions are 8 bits long.
  • 4 registers: R0 = 00, R1 = 01, R2 = 10, R3 = 11.
  • Meaning: dest ← dest op source.
  • A 4-bit opcode can define at most 24 = 16 operations; 5 are used here.
Example: 0001 10 11 → ADD R2, R3 → R2 ← R2 + R3

Machine Language

Sample Program: Splitting the Fields

Machine codeOperationDestSourceMeaning
0001 0001ADDR0R1R0 ← R0 + R1
0011 1011ANDR2R3R2 ← R2 AND R3
0100 0110ORR1R2R1 ← R1 OR R2
0000 0000HALT——stop the program
In this format the first 2-bit field is the destination, so the result goes to the first register (R0, R2, R1).

In hex: 11h, 3Bh, 46h, 00h.

Machine Language · Step through the code

Code Trace: The Sample Machine Program

Initial values (example). PC = 0: the first instruction is about to be fetched.

ADD R0, R1: 5 + 3 = 8 → R0. The source (R1) does not change.

AND R2, R3: 1100 AND 1010 = 1000 → R2 = 8. Only bits that are 1 on both sides survive.

OR R1, R2: 0011 OR 1000 = 1011 → R1 = 11.

HALT: the processor stops. Result: R0 = 8, R1 = 11, R2 = 8, R3 = 10.

0001 0001   ; ADD R0, R1 → R0 ← R0 + R1
0011 1011   ; AND R2, R3 → R2 ← R2 AND R3
0100 0110   ; OR  R1, R2 → R1 ← R1 OR R2
0000 0000   ; HALT

Machine Language

Machine Language: Pros and Cons

Pros

  • No translation needed; the processor runs it directly.
  • Full control over the hardware.
  • The smallest and (if written well) fastest code.

Cons

  • Very hard to read, write and debug.
  • Addresses are computed by hand; inserting one instruction breaks every jump address.
  • Not portable: rewritten from scratch for each processor.
  • A single bit error changes the program completely.
beforeJMP 0105h0100hMOV …0103htarget: ADD …0105h2-byte instruction insertedJMP 0105h0100hNEW0103hMOV …0105htarget: ADD …0107hJMP still goes to 0105h ✗
To fix these problems, first assembly languages (1950s) and then high-level languages such as FORTRAN (1957) were developed.

Assembly Languages

Assembly Languages

  • Each machine instruction is written as a memorable mnemonic: MOV AL, 5 instead of 10110000 00000101.
  • Each is tied to an architecture and instruction set: Intel x86, Motorola 68000, ARM, PIC and AVR each have their own assembly language.
  • Microcontroller assembly languages are common in embedded systems and electronics.
  • They let the programmer make the most of the hardware.
  • The program that translates source code into machine language is the assembler.
MOV AL, 5assemblerB0 05=10110000 00000101
Where is it used?bootloaders, device drivers, interrupt routines, OS kernels
Why learn it?understanding how the processor works, debugging, reverse engineering
Performancespecial instructions compilers cannot generate (SIMD, crypto) and critical loops

Assembly Languages

From Source Code to a Running Program

prog.asmsource assembler prog.objobject code linker prog.exeexecutable + libraries (.lib/.obj) MASM, NASM, TASM, GASLINK, ld loader → memory

The assembler's listing shows each line's address and machine code side by side:

Address Machine code  Source
0100    B4 09         mov ah, 09h
0102    BA 0C 01      mov dx, offset msg
0105    CD 21         int 21h
0107    B8 00 4C      mov ax, 4C00h
010A    CD 21         int 21h
010C    57 65 6C ...  msg db 'Welcome!$'

emu8086 runs all these steps with one key and produces the COM/EXE file directly.

Assembly Languages · Step through the code

Code Trace: The Assembler's Two Passes

org 100h
mov ah, 09h
mov dx, offset msg
int 21h
mov ax, 4C00h
int 21h
msg db 'Welcome!$'
PASS 1location counter (LC)0100hsymbol tablemsg?generated bytes(no bytes in pass 1)line 1

Pass 1 only counts addresses. org 100h sets the location counter (LC) to 0100h; a directive generates no bytes.

PASS 1location counter (LC)0102hsymbol tablemsg?generated bytes(no bytes in pass 1)line 2

mov ah, 09h takes 2 bytes → LC = 0102h. The bytes themselves are not written yet.

PASS 1location counter (LC)0105hsymbol tablemsg?generated bytes(no bytes in pass 1)line 3

offset msg is a forward reference: msg is not defined yet, but the instruction is known to be 3 bytes → LC = 0105h.

PASS 1location counter (LC)010Chsymbol tablemsg?generated bytes(no bytes in pass 1)lines 4, 5, 6

int 21h (2), mov ax, 4C00h (3), int 21h (2): LC = 010Ch.

PASS 1location counter (LC)0115hsymbol tablemsg010Chgenerated bytes(no bytes in pass 1)line 7

The label msg enters the symbol table with the current LC: msg = 010Ch. A 9-byte string → LC = 0115h.

PASS 2location counter (LC)0100hsymbol tablemsg010Chgenerated bytesB409line 2

Pass 2 starts over and generates the bytes: mov ah, 09h → B4 09.

PASS 2location counter (LC)0102hsymbol tablemsg010Chgenerated bytesB409BA0C01line 3

offset msg now comes from the table: 010Ch → BA 0C 01 (address little-endian).

PASS 2location counter (LC)0105hsymbol tablemsg010Chgenerated bytesB409BA0C01CD21B8004CCD21lines 4, 5, 6

The remaining instructions: CD 21, B8 00 4C, CD 21.

PASS 2location counter (LC)010Chsymbol tablemsg010Chgenerated bytesB409BA0C01CD21B8004CCD2157656C636F6D652124line 7

The string's ASCII codes are written: 57 65 6C … 24 ('$'). The output is a 21-byte COM file; when run it prints Welcome!.

Assembly Languages

Assemblers and Their Syntax

AssemblerSyntax · use
MASMIntel · Microsoft, Windows
TASMIntel · Borland, DOS
NASMIntel · open source, cross-platform
GAS (as)AT&T · GNU/Linux, gcc
emu8086Intel (MASM-like) · 8086 emulator, this course

One instruction, two notations

; Intel:  dest, source
mov eax, 5
add eax, [ebx+4]

# AT&T:  source, dest
movl $5, %eax
addl 4(%ebx), %eax

In AT&T, registers take % and constants take $; the size is given by an instruction suffix (l = 32 bits).

Assembly Languages · Step through the code

x86 Assembly: Linux (32-bit, NASM)

Data section: the string plus a newline (10). len is computed as 16 by $ - hello.

The program starts at _start. EAX = 4: the sys_write system call number.

EBX = 1: the file descriptor to write to, stdout (the screen).

ECX = the string's address (not its contents).

EDX = 16 (10h): the number of bytes to write.

int 0x80: the kernel is called and the text is written. On return EAX = bytes written (16).

EAX = 1: sys_exit.

xor ebx, ebx: a number XORed with itself is 0 → exit code 0 (success). Shorter than mov ebx, 0.

The kernel ends the process with exit code 0; this call never returns.

section .data
hello  db 'Welcome, Linux!', 10
len    equ $ - hello     ; = 16 bytes
section .text
global _start
_start:
  mov eax, 4     ; sys_write
  mov ebx, 1     ; stdout
  mov ecx, hello ; string address
  mov edx, len   ; byte count
  int 0x80       ; call the kernel
  mov eax, 1     ; sys_exit
  xor ebx, ebx   ; exit code 0
  int 0x80

“Welcome, Linux!” is 15 bytes; the trailing newline (10) makes the string 16 bytes. equ $ - hello lets the assembler compute the length.

Assembly Languages

How Does a System Call Work?

User programEAX=4 EBX=1ECX=addr EDX=16 Kernelpicks the service froma table by EAX Driver · hardwareterminal / screen int 0x80 EAX = result user modekernel mode (privileged)
EnvironmentCallService numberParameters
Linux 32-bitint 0x80EAX (4 = write, 1 = exit)EBX, ECX, EDX
Linux 64-bitsyscallRAX (1 = write, 60 = exit)RDI, RSI, RDX
MS-DOSint 21hAH (09h = print, 4Ch = exit)DX, AL …
BIOSint 10hAH (0Eh = print char)AL, BH …

Assembly Languages · Step through the code

x86 Assembly: DOS (emu8086, COM)

org 100h: a COM program is loaded at offset 100h of its segment (the 256 bytes before it are the PSP). CS = DS = ES = SS.

AH = 09h: the DOS service “print a string ending in $”.

lea dx, msg: DS:DX points to the string. The code is 12 bytes (0100h–010Bh), so msg is at 010Ch.

int 21h: DOS prints characters until it sees '$' (the '$' itself is not printed).

AX = 4C00h: AH = 4Ch “terminate the program”, AL = 00h exit code.

The program ends and control returns to DOS. The data sits after the code, so the processor never mistakes it for instructions.

org 100h          ; COM program
mov ah, 09h       ; DOS 09h: print string
lea dx, msg       ; DS:DX = address
int 21h           ; call DOS
mov ax, 4C00h     ; DOS 4Ch: exit
int 21h
msg db 'Welcome, DOS!$'

Service 09h expects a '$' terminator; the data goes after the code; placed before it, it would be executed. mov ax, 4C00h also clears AL (the exit code).

Assembly Languages

x86 Assembly: Windows (Win32 API, NASM)

extern MessageBoxA    ; user32.dll
extern ExitProcess    ; kernel32.dll

section .data
msg db 'Welcome, Windows!', 0

section .text
global _start
_start:
    push 0          ; uType = MB_OK
    push msg        ; lpCaption (title)
    push msg        ; lpText (text)
    push 0          ; hWnd = NULL
    call MessageBoxA
    push 0          ; uExitCode = 0
    call ExitProcess
Differences
  • No system call: OS services are called as DLL functions.
  • Parameters are pushed onto the stack right to left: MessageBoxA(hWnd, lpText, lpCaption, uType) in C.
  • stdcall: the called function cleans up the stack.
  • Strings end with 0 (C strings).
  • Linking may need the decorated name: _MessageBoxA@16 (16 = parameter bytes).

Assembly Languages · Step through the code

Code Trace: Parameters onto the Stack

high address ↑0012FF80h0012FF7Ch0012FF78h0012FF74h0012FF70h0012FF6Chlow address ↓ (the stack grows this way)ESP→

Start: ESP = 0012FF80h (sample value). The stack grows toward lower addresses.

high address ↑0012FF80h0012FF7Ch0uType = MB_OK0012FF78h0012FF74h0012FF70h0012FF6Chlow address ↓ (the stack grows this way)ESP→

push 0: ESP drops by 4; the last parameter (uType) is pushed first.

high address ↑0012FF80h0012FF7Ch0uType = MB_OK0012FF78h&msglpCaption0012FF74h0012FF70h0012FF6Chlow address ↓ (the stack grows this way)ESP→

push msg: the address of the caption string is pushed.

high address ↑0012FF80h0012FF7Ch0uType = MB_OK0012FF78h&msglpCaption0012FF74h&msglpText0012FF70h0012FF6Chlow address ↓ (the stack grows this way)ESP→

push msg: the address of the text string.

high address ↑0012FF80h0012FF7Ch0uType = MB_OK0012FF78h&msglpCaption0012FF74h&msglpText0012FF70h0hWnd = NULL0012FF6Chlow address ↓ (the stack grows this way)ESP→

push 0: the first parameter (hWnd) is pushed last → it sits on top. Parameters go on right to left.

high address ↑0012FF80h0012FF7Ch0uType = MB_OK0012FF78h&msglpCaption0012FF74h&msglpText0012FF70h0hWnd = NULL0012FF6Chreturn addrinstruction after calllow address ↓ (the stack grows this way)ESP→

call MessageBoxA: the return address is pushed and control jumps to the function; a message box opens.

high address ↑0012FF80h0012FF7Ch0012FF78h0012FF74h0012FF70h0012FF6Chlow address ↓ (the stack grows this way)ESP→

When the user clicks OK, the function returns with ret 16: under stdcall the callee cleans the stack, so ESP is 0012FF80h again. EAX = 1 (IDOK).

high address ↑0012FF80h0012FF7Ch0uExitCode = 00012FF78h0012FF74h0012FF70h0012FF6Chlow address ↓ (the stack grows this way)ESP→

push 0 + call ExitProcess: the process ends with exit code 0; this call never returns.

extern MessageBoxA
extern ExitProcess
section .data
msg db 'Welcome...', 0
section .text
global _start
_start:
  push 0       ; uType
  push msg     ; lpCaption
  push msg     ; lpText
  push 0       ; hWnd
  call MessageBoxA
  push 0       ; uExitCode
  call ExitProcess

Assembly Languages

Motorola 68000 Assembly: Amiga

    move.l  4.w,a6         ; a6 = ExecBase
    lea     dosname(pc),a1 ; library name
    moveq   #0,d0          ; any version
    jsr     -552(a6)       ; OpenLibrary()
    tst.l   d0
    beq.s   quit           ; failed → quit
    move.l  d0,a6          ; a6 = DOSBase
    jsr     -60(a6)        ; Output() → d0
    move.l  d0,d1          ; file handle
    move.l  #msg,d2        ; string address
    moveq   #16,d3         ; byte count
    jsr     -48(a6)        ; Write(d1,d2,d3)
    move.l  a6,a1
    move.l  4.w,a6
    jsr     -414(a6)       ; CloseLibrary()
quit moveq  #0,d0          ; return code 0
    rts
dosname dc.b 'dos.library',0
msg     dc.b 'Welcome, Amiga!',10
Differences
  • 8 data registers (d0–d7) and 8 address registers (a0–a7); source, destination order.
  • Size suffixes: .b, .w, .l; constants take #.
  • Services are called at negative offsets from the library base (-48(a6)).
  • The library is opened, used and closed.

Assembly Languages

ARM Assembly: Linux (32-bit, GNU as)

    .data
msg:    .ascii "Welcome, ARM!\n"
len = . - msg          @ 14 bytes

    .text
    .global _start
_start:
    mov  r7, #4        @ sys_write
    mov  r0, #1        @ stdout
    ldr  r1, =msg      @ string address
    mov  r2, #len      @ byte count
    svc  #0            @ call the kernel
    mov  r7, #1        @ sys_exit
    mov  r0, #0        @ exit code
    svc  #0
Differences
  • RISC: 16 registers (r0–r15), fixed 32-bit instructions.
  • The service number goes in r7, parameters in r0–r2.
  • Entering the kernel: svc #0 (formerly swi).
  • Memory is read and written only with ldr/str.

GNU as uses .ascii, not db; . - msg lets the assembler compute the length.

Assembly Languages

PowerPC (PPC) Assembly: Linux (32-bit)

    .data
msg:    .ascii "Welcome, PowerPC!\n"
len = . - msg           # 18 bytes

    .text
    .globl _start
_start:
    li   0, 4           # r0 = sys_write
    li   3, 1           # r3 = stdout
    lis  4, msg@ha      # r4 = addr (high)
    addi 4, 4, msg@l    #    + low half
    li   5, len         # r5 = byte count
    sc                  # call the kernel
    li   0, 1           # r0 = sys_exit
    li   3, 0           # r3 = exit code
    sc
Differences
  • RISC: 32 general registers; GNU as writes registers as plain numbers (3 = r3).
  • The service number goes in r0, parameters in r3, r4, r5; the trap is sc.
  • A 32-bit address is loaded in two 16-bit halves (@ha, @l).

Assembly Languages

One “Welcome”, Six Environments

EnvironmentProcessorEntering the OSService no.ParametersString end
Linuxx86 (32)int 0x80EAXEBX, ECX, EDXlength given
DOS8086int 21hAHDX (address)'$'
Windowsx86 (32)call to a DLLfunction namestack0
AmigaOS68000jsr -48(a6)library offsetd1, d2, d3length given
LinuxARMsvc #0r7r0, r1, r2length given
LinuxPowerPCscr0r3, r4, r5length given
Assembly code depends on both the processor (instruction set, registers) and the operating system (call mechanism, numbers). Even the comment character depends on the syntax: ; on x86, @ in ARM GNU, # on PowerPC. The big win of high-level languages is handing this dependence to the compiler or interpreter.

High-Level Languages

High-Level Languages

Compiled languages
  • Source code is translated to machine language ahead of time.
  • Most errors are caught at compile time.
  • The code runs faster.
  • Stages: compiling (compiler) and linking (linker).
  • The output is specific to one processor + operating system.
Interpreted languages
  • Source code is processed by an interpreter at run time.
  • Allows fast development and experimentation.
  • Source code is platform-independent: it runs wherever an interpreter exists.
  • Errors may only appear when the line in question runs.
  • Usually slower.
compiledsourcecompilermachine codeCPUinterpretedsourceinterpreter (at run time)CPUhybridsourcecompilerintermediate codeVM + JITCPU
The hybrid approach: Java and C# are first compiled to intermediate code (bytecode/IL); the virtual machine translates it to machine language while running (JIT, just-in-time). Python and JavaScript engines also use bytecode/JIT internally.

High-Level Languages · Step by step

The Compilation Process (C, gcc)

1 · Preprocessor#include and #define are expanded → oddeven.i (gcc -E)
2 · CompilerC code is syntax- and type-checked and translated to assembly → oddeven.s (gcc -S)
3 · AssemblerAssembly is translated to machine code → object file oddeven.o (gcc -c)
4 · LinkerThe object file is combined with library code such as printf/scanf → executable oddeven / oddeven.exe
5 · LoaderThe operating system loads the program into memory and jumps to main.

In one command: gcc oddeven.c -o oddeven. To see the intermediate assembly: gcc -S -masm=intel oddeven.c.

High-Level Languages · Step through the code

Code Trace: A Loop the Compiler Generated

org 100h
mov bx, 0         ; sum = 0
mov cx, 10        ; i = 10
cond: cmp cx, 0   ; i > 0 ?
jle done
add bx, cx        ; sum += i
sub cx, 3         ; i -= 3
jmp cond
done: mov sum, bx
ret
sum dw ?
C sourcesum = 0;i = 10;while (i > 0) { sum += i; i -= 3;}sum (BX)0i (CX)1010 + 7 + 4 + 1 = 22

The compiler put the variables in registers: sum → BX, i → CX. The while condition is tested at the top of the loop.

C sourcesum = 0;i = 10;while (i > 0) { sum += i; i -= 3;}sum (BX)0i (CX)10cmp: i − 0 → ZF=0 SF=0 OF=0jle not taken → body10 + 7 + 4 + 1 = 22

cmp cx, 0 + jle: i = 10 > 0, so no jump; the body runs (the C condition was inverted into an “exit” jump).

C sourcesum = 0;i = 10;while (i > 0) { sum += i; i -= 3;}sum (BX)10i (CX)710 + 7 + 4 + 1 = 22

Body: sum = 10, i = 7; jmp cond goes back to the test.

C sourcesum = 0;i = 10;while (i > 0) { sum += i; i -= 3;}sum (BX)10i (CX)7cmp: i − 0 → ZF=0 SF=0 OF=0jle not taken → body10 + 7 + 4 + 1 = 22

cmp cx, 0 + jle: i = 7 > 0, so no jump; the body runs (the C condition was inverted into an “exit” jump).

C sourcesum = 0;i = 10;while (i > 0) { sum += i; i -= 3;}sum (BX)17i (CX)410 + 7 + 4 + 1 = 22

Body: sum = 17, i = 4; jmp cond goes back to the test.

C sourcesum = 0;i = 10;while (i > 0) { sum += i; i -= 3;}sum (BX)17i (CX)4cmp: i − 0 → ZF=0 SF=0 OF=0jle not taken → body10 + 7 + 4 + 1 = 22

cmp cx, 0 + jle: i = 4 > 0, so no jump; the body runs (the C condition was inverted into an “exit” jump).

C sourcesum = 0;i = 10;while (i > 0) { sum += i; i -= 3;}sum (BX)21i (CX)110 + 7 + 4 + 1 = 22

Body: sum = 21, i = 1; jmp cond goes back to the test.

C sourcesum = 0;i = 10;while (i > 0) { sum += i; i -= 3;}sum (BX)21i (CX)1cmp: i − 0 → ZF=0 SF=0 OF=0jle not taken → body10 + 7 + 4 + 1 = 22

cmp cx, 0 + jle: i = 1 > 0, so no jump; the body runs (the C condition was inverted into an “exit” jump).

C sourcesum = 0;i = 10;while (i > 0) { sum += i; i -= 3;}sum (BX)22i (CX)-210 + 7 + 4 + 1 = 22

Body: sum = 22, i = -2; jmp cond goes back to the test.

C sourcesum = 0;i = 10;while (i > 0) { sum += i; i -= 3;}sum (BX)22i (CX)-2cmp: i − 0 → ZF=0 SF=1 OF=0jle taken → done10 + 7 + 4 + 1 = 22

i = -2: the condition i > 0 is false (i ≤ 0, SF ≠ OF) → jle done jumps and the loop exits.

C sourcesum = 0;i = 10;while (i > 0) { sum += i; i -= 3;}sum (BX)22i (CX)-2sum ← BX = 2210 + 7 + 4 + 1 = 22

The result is stored: sum = 22. One C loop became a compare, a conditional jump and an unconditional jump.

High-Level Languages · Compiled

Compiled Languages

  • The compiler examines the whole source before it runs.
  • Compiled code runs directly on the processor, so it is faster.
  • Type and syntax errors are caught at compile time.
C and C++systems programming, operating systems, embedded software, high-performance applications
Rustsafe, fast systems programming (memory safety checked by the compiler)
Fortranscientific and numerical computing; the first widely used high-level language (1957)
Goserver and network software; fast compilation, concurrency
Adasafety-critical systems such as aviation, defense and railways
Java, C# (hybrid)compiled to intermediate code, run with a JIT on a virtual machine

High-Level Languages · Step through the code

Task: Odd/Even from 1 to n — C

Every sample program does the same job: read a number, then print whether each number from 1 to it is odd or even.

The user enters 3. scanf gets the variable's address (&number).

The loop starts: i = 1, the condition 1 ≤ 3 is true.

1 % 2 = 1 ≠ 0 → the else branch: “odd”.

i++ → 2; 2 ≤ 3 is true.

2 % 2 = 0 → “even”.

i = 3; 3 ≤ 3 is true.

3 % 2 = 1 → “odd”.

i = 4; 4 ≤ 3 is false → the loop ends.

return 0: a “success” exit code for the operating system.

#include <stdio.h>

int main() {
    int number;
    printf("Enter a number: ");
    scanf("%d", &number);
    for (int i = 1; i <= number; i++) {
        if (i % 2 == 0) {
            printf("%d is even.\n", i);
        } else {
            printf("%d is odd.\n", i);
        }
    }
    return 0;
}

High-Level Languages · Compiled

C++

#include <iostream>

int main() {
    int number;
    std::cout << "Enter a number: ";
    std::cin >> number;
    for (int i = 1; i <= number; i++) {
        if (i % 2 == 0) {
            std::cout << i << " is even."
                      << std::endl;
        } else {
            std::cout << i << " is odd."
                      << std::endl;
        }
    }
    return 0;
}
C++ (1985, Bjarne Stroustrup)
  • A superset of C; classes, templates, exceptions.
  • Streams for I/O: std::cout << writes, std::cin >> reads.
  • Build: g++ oddeven.cpp -o oddeven
  • std::endl adds a newline and flushes the buffer; for many lines '\n' is faster.

High-Level Languages · Compiled (to intermediate code)

C#

using System;

class Program {
  static void Main() {
    Console.Write("Enter a number: ");
    int number = int.Parse(Console.ReadLine());
    for (int i = 1; i <= number; i++) {
      if (i % 2 == 0) {
        Console.WriteLine($"{i} is even.");
      } else {
        Console.WriteLine($"{i} is odd.");
      }
    }
  }
}
C# (2000, Microsoft)
  • The .NET platform; compiled to the IL intermediate language, which the CLR JIT-compiles to machine code at run time.
  • $"{i} …": string interpolation.
  • Run: dotnet run
  • int.Parse throws an exception on non-numeric input; int.TryParse is safer.

High-Level Languages · Compiled (bytecode)

Java

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter a number: ");
    int number = scanner.nextInt();
    for (int i = 1; i <= number; i++) {
      if (i % 2 == 0) {
        System.out.println(i + " is even.");
      } else {
        System.out.println(i + " is odd.");
      }
    }
  }
}
Java (1995, Sun Microsystems)
  • javac → platform-independent bytecode (.class) → JIT on the JVM.
  • “Write once, run anywhere.”
  • Run: javac Main.java and java Main
  • Everything lives in a class; the file name = the public class name.

High-Level Languages · Compiled

Go

package main

import "fmt"

func main() {
    var number int
    fmt.Print("Enter a number: ")
    fmt.Scan(&number)
    for i := 1; i <= number; i++ {
        if i%2 == 0 {
            fmt.Printf("%d is even.\n", i)
        } else {
            fmt.Printf("%d is odd.\n", i)
        }
    }
}
Go (2009, Google)
  • Compiles straight to machine code; one self-contained executable.
  • A garbage collector and lightweight threads (goroutines).
  • Run: go run oddeven.go
  • No parentheses around conditions and loops; := infers the type.

High-Level Languages · Compiled

Rust

use std::io;

fn main() {
    let mut input = String::new();
    println!("Enter a number:");
    io::stdin().read_line(&mut input)
        .expect("read error");
    let number: i32 = input.trim().parse()
        .expect("parse error");
    for i in 1..=number {
        if i % 2 == 0 {
            println!("{} is even.", i);
        } else {
            println!("{} is odd.", i);
        }
    }
}
Rust (2015, Mozilla)
  • Memory safety without a garbage collector: ownership rules are checked by the compiler.
  • Variables are immutable by default; you need mut.
  • 1..=number: a range that includes the upper bound.
  • Run: rustc oddeven.rs or cargo run

High-Level Languages · Compiled

Fortran

program Main
    implicit none
    integer :: number, i
    write(*,*) 'Enter a number:'
    read(*,*) number
    do i = 1, number
        if (mod(i, 2) == 0) then
            write(*,*) i, ' is even.'
        else
            write(*,*) i, ' is odd.'
        end if
    end do
end program Main
Fortran (1957, IBM · John Backus)
  • The first widely used high-level language: FORmula TRANslation.
  • Still common in scientific computing (weather forecasting, physics).
  • implicit none: every variable must be declared explicitly.
  • Run: gfortran oddeven.f90 -o oddeven
  • write(*,*) uses free format; numbers may print with leading spaces.

High-Level Languages · Compiled

Ada

with Ada.Text_IO;         use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure Main is
   Number : Integer;
begin
   Put ("Enter a number: ");
   Get (Number);
   for I in 1 .. Number loop
      Put (I, Width => 0);
      if I mod 2 = 0 then
         Put_Line (" is even.");
      else
         Put_Line (" is odd.");
      end if;
   end loop;
end Main;
Ada (1983, US Department of Defense)
  • Strong type checking; aviation and defense software.
  • Run: gnatmake main.adb
  • Integer Get/Put need Ada.Integer_Text_IO; Put_Line adds a newline.

High-Level Languages · Interpreted

Interpreted Languages

  • Source code is interpreted at run time; there is no separate compile step.
  • Fast development and experimentation (interactive shell, REPL).
Pythongeneral-purpose, high-level; data science, AI
JavaScriptweb development; runs in the browser and in Node.js
Rubyease of use and flexibility; Ruby on Rails
oddeven.py interpreter (CPython) read the next statement parse (to bytecode) run

High-Level Languages · Interpreted

Python

# Read input from the user
number = int(input("Enter a number: "))

# Check the numbers from 1 to number
for i in range(1, number + 1):
    if i % 2 == 0:
        print(f"{i} is even.")
    else:
        print(f"{i} is odd.")
Python (1991, Guido van Rossum)
  • Blocks are marked by indentation, not braces.
  • range(1, number + 1): the upper bound is excluded, hence the +1.
  • input returns text; int(...) converts it to a number.
  • Run: python oddeven.py
  • Dynamically typed: a variable's type is decided at run time.
The job that takes 15 lines in C takes 6 here: the expressiveness of high-level languages. The price: CPython runs the same loop tens of times slower than C.

High-Level Languages · Interpreted (JIT)

JavaScript

// Read input from the user
let number = Number(prompt("Enter a number:"));

// Check the numbers from 1 to number
for (let i = 1; i <= number; i++) {
    if (i % 2 === 0) {
        console.log(i + " is even.");
    } else {
        console.log(i + " is odd.");
    }
}
JavaScript (1995, Brendan Eich)
  • The language of browsers; runs on servers too with Node.js.
  • Modern engines (V8) JIT-compile the code to machine code.
  • prompt returns text; convert it with Number(...).
  • ===: equality without type conversion.

High-Level Languages · Interpreted

Ruby

# Read input from the user
print "Enter a number: "
number = gets.chomp.to_i

# Check the numbers from 1 to number
for i in 1..number do
  if i % 2 == 0
    puts "#{i} is even."
  else
    puts "#{i} is odd."
  end
end
Ruby (1995, Yukihiro Matsumoto)
  • Everything is an object: gets.chomp.to_i is a chain of method calls.
  • chomp drops the newline, to_i converts to an integer.
  • 1..number: a range that includes the upper bound.
  • "#{i}": string interpolation.
  • Run: ruby oddeven.rb

High-Level Languages · Interpreted

PHP

<?php
// Read input from the user
echo "Enter a number: ";
$number = (int) trim(fgets(STDIN));

// Check the numbers from 1 to number
for ($i = 1; $i <= $number; $i++) {
    if ($i % 2 == 0) {
        echo $i . " is even.\n";
    } else {
        echo $i . " is odd.\n";
    }
}
?>
PHP (1995, Rasmus Lerdorf)
  • A server-side web language; can be embedded in HTML.
  • Variables start with $; . concatenates strings.
  • fgets(STDIN) reads a line from the command line; trim drops the newline.
  • Run: php oddeven.php

High-Level Languages · Interpreted

Perl

use strict;
use warnings;

# Read input from the user
print "Enter a number: ";
my $number = <STDIN>;
chomp $number;

# Check the numbers from 1 to number
for my $i (1..$number) {
    if ($i % 2 == 0) {
        print "$i is even.\n";
    } else {
        print "$i is odd.\n";
    }
}
Perl (1987, Larry Wall)
  • Text processing and system administration; powerful regular expressions.
  • <STDIN> reads a line, chomp drops the newline.
  • In a double-quoted string $i is replaced by its value.
  • use strict; use warnings; catch common mistakes.
  • Run: perl oddeven.pl

High-Level Languages · Interpreted

MATLAB

% Read input from the user
number = input('Enter a number: ');

% Check the numbers from 1 to number
for i = 1:number
    if mod(i, 2) == 0
        fprintf('%d is even.\n', i);
    else
        fprintf('%d is odd.\n', i);
    end
end
MATLAB (1984, MathWorks)
  • Matrix-based numerical computing; common in engineering, especially signal processing and control.
  • 1:number: the vector 1, 2, …, number.
  • A ; at the end of a line suppresses printing the result.
  • A free, compatible alternative: GNU Octave.

High-Level Languages

One Program, Fourteen Languages

LanguageModelLoop headerRemainderOutput
Ccompiledfor (int i = 1; i <= n; i++)i % 2printf
C++compiledfor (int i = 1; i <= n; i++)i % 2std::cout <<
C#IL + JITfor (int i = 1; i <= n; i++)i % 2Console.WriteLine
Javabytecode + JITfor (int i = 1; i <= n; i++)i % 2System.out.println
Gocompiledfor i := 1; i <= n; i++i%2fmt.Printf
Rustcompiledfor i in 1..=ni % 2println!
Fortrancompileddo i = 1, nmod(i, 2)write(*,*)
Adacompiledfor I in 1 .. N loopI mod 2Put_Line
Pythoninterpretedfor i in range(1, n + 1):i % 2print
JavaScriptinterpreted/JITfor (let i = 1; i <= n; i++)i % 2console.log
Rubyinterpretedfor i in 1..n doi % 2puts
PHPinterpretedfor ($i = 1; $i <= $n; $i++)$i % 2echo
Perlinterpretedfor my $i (1..$n)$i % 2print
MATLABinterpreted/JITfor i = 1:nmod(i, 2)fprintf

High-Level Languages

Compiled, Interpreted, Hybrid

CriterionCompiledInterpretedHybrid (bytecode + JIT)
Translation timeonce, before runningon every runfirst to intermediate code, then at run time
Speedhighestlowesthigh (after warm-up)
What shipsmachine codesource codeintermediate code (.class, .dll)
Portabilityrecompile for each platformanywhere with an interpreteranywhere with a virtual machine
Error detectionmostly at compile timemostly at run timetype errors at compile time
ExamplesC, C++, Go, Rust, Fortran, AdaPython, Ruby, PHP, Perl, MATLABJava, C#, JavaScript (V8)
“Compiled/interpreted” is a property of the implementation, not the language: there are interpreters for C and compilers for Python (Cython, PyPy JIT).

High-Level Languages · Step through the code

Code Trace: How Does Bytecode Run?

// x = (a + b) * c;
iload a      // push a
iload b      // push b
iadd         // add the top two
iload c
imul         // multiply the top two
istore x     // pop into x
return
operand stack6← toplocal variablesa6b7c3x?

For x = (a + b) * c the compiler generated stack-based intermediate code (bytecode). Locals: a = 6, b = 7, c = 3. iload a: local a = 6 is pushed onto the stack.

operand stack67← toplocal variablesa6b7c3x?

iload b: local b = 7 is pushed onto the stack.

operand stack13← toplocal variablesa6b7c3x?

iadd: the top two items (6, 7) are popped and the sum 13 is pushed. No operand names; everything is on the stack.

operand stack133← toplocal variablesa6b7c3x?

iload c: local c = 3 is pushed onto the stack.

operand stack39← toplocal variablesa6b7c3x?

imul: 13 × 3 = 39 is pushed.

operand stacklocal variablesa6b7c3x39

istore x: the top of the stack is stored in x → x = 39; the stack is empty.

operand stacklocal variablesa6b7c3x39

This intermediate code is tied to no processor: the virtual machine (JVM, CLR) either interprets each instruction or JIT-compiles it into real machine code such as 8086/x86.

Bridge · Step through the code

The Same Task in 8086 Assembly (n = 3)

CX serves as the counter (i): i = 1. n = 3 is hard-coded; it is not read from the keyboard.

cmp cx, 3: computes 1 − 3 (the result is discarded) → ZF=0, CF=1 (borrow). ja jumps only if CF=0 and ZF=0 → no jump.

DL = 1 + 30h = 31h: the ASCII code of the digit 1. ADD updates the flags: CF=0.

DOS service 02h prints the character in DL.

test cl, 1: 1 AND 1 = 1 ≠ 0 → ZF=0 → jnz odd jumps. (The lowest bit instead of i % 2.)

DX = the address of the odd_m string; service 09h prints up to the '$'. 0Dh, 0Ah are carriage return + line feed.

inc cx → 2 (INC does not change CF); back to the top of the loop.

2 − 3: CF=1 → continue.

DL = 32h ('2') is printed.

2 AND 1 = 0 → ZF=1 → jnz does not jump: the number is even.

DX = even_m; jmp print goes to the shared print code.

The “even” message is printed.

CX = 3.

3 − 3 = 0 → ZF=1, CF=0. Since ZF=1, ja does not jump (3 ≤ 3).

'3' is printed; 3 AND 1 = 1 → ZF=0 → odd.

The “odd” message is printed.

CX = 4.

4 − 3 = 1 → ZF=0, CF=0 → ja done jumps (4 > 3).

ret: the COM program returns to DOS. C's for + if became pairs of compare + conditional jump.

org 100h
       mov  cx, 1       ; i = 1
again: cmp  cx, 3       ; compare i with n
       ja   done        ; done if i > n
       mov  dl, cl
       add  dl, '0'     ; digit → ASCII
       mov  ah, 02h
       int  21h         ; print DL
       test cl, 1       ; lowest bit
       jnz  odd         ; 1 means odd
       lea  dx, even_m
       jmp  print
odd:   lea  dx, odd_m
print: mov  ah, 09h
       int  21h         ; print string
       inc  cx          ; i++
       jmp  again
done:  ret
odd_m  db ' is odd.',0Dh,0Ah,'$'
even_m db ' is even.',0Dh,0Ah,'$'

Summary

Summary

  • Software runs the hardware; the operating system is the core software, and programming languages are used to build software.
  • Machine language is the only language the processor understands: binary instructions made of opcode and operand fields; fully hardware-dependent.
  • Assembly language writes machine instructions as mnemonics; the assembler and linker turn it into an executable. The code depends on both the processor and the operating system (int 0x80, int 21h, DLL calls, svc, sc).
  • Compiled languages (C, C++, Go, Rust, Fortran, Ada) are translated to machine code ahead of time: fast, but platform-specific.
  • Interpreted languages (Python, JavaScript, Ruby, PHP, Perl, MATLAB) are processed at run time: fast development, portable source, slower execution. Java/C# sit in between with intermediate code + JIT.
  • A high-level for/if is implemented in assembly as compare + conditional jump.

Summary

Exercises

  1. Encode SUB R3, R0 and OR R0, R2 in binary and hex.
  2. Decode the instruction 0010 0111. If R1 = 9 and R3 = 4, what is the result?
  3. How many opcodes fit in this design? How must the format change for 8 registers?
  4. What happens if the DOS program's string lacks the final '$'?
  5. In the Linux example, what would be printed if len were hard-coded as 15?
  6. Windows example: why are parameters pushed in reverse? What is ESP right after the call?
  7. Why can't Java be labeled simply “compiled” or “interpreted”?
Hints / answers
  1. 0010 1100 = 2Ch; 0100 0010 = 42h.
  2. SUB R1, R3 → R1 ← 9 − 4 = 5.
  3. 24 = 16. 8 registers need 3 bits each: 4 + 3 + 3 = 10 bits. To stay at 8 bits the opcode shrinks to 2 bits: only 4 operations fit, not five.
  4. DOS prints random bytes from memory until it hits the first '$' character.
  5. “Welcome, Linux!” is printed, but not the newline (the 16th byte).
  6. C convention: the first parameter must be on top; 4 pushes + return address → ESP = 0012FF80h − 20 = 0012FF6Ch.
  7. Compiled to bytecode, then interpreted or JIT-compiled on the JVM: a hybrid.

Summary

References

  • Tanenbaum and Bos, Modern Operating Systems, 3rd ed., Pearson.
  • Brey, The Intel Microprocessors, 8th ed., Pearson.
  • Irvine, Assembly Language for x86 Processors, 7th ed., Pearson.
  • NASM documentation (nasm.us) and the GNU Binutils as manual.
  • Ralf Brown's Interrupt List (DOS INT 21h services); Microsoft Win32 API documentation (MessageBoxA, ExitProcess).
  • emu8086 documentation and 8086 instruction set reference.

The End

Chapter 3.1: Programming Languages
Previous: Chapter 2.2: 8086 Registers · Next: Chapter 3.2: Assembly Language
1 / 1 Sercan KÜLCÜ. All rights reserved.