In the assembly post we wrote variables directly at the end of
the program and named them, as in num: DATA 7. How do we make variables in C,
and what instructions does the compiler turn them into?
A C program is written between int main(void) { and }, as below. What this
frame means is covered in the functions post, so for now treat
it as a fixed frame and look only at the lines inside the braces. Lines run from
top to bottom, and each ends with ;.
int main(void) {
// the lines written here run from top to bottom
}
A line that starts with a type, like char a = 2;, is a declaration that
makes a variable a. char is a type that holds an integer in one slot of
memory, or 1 byte. Once declared, you change the value by writing just the name,
without the type, as in a = 5;. The compiler sets aside one slot after the
program and labels it a.
c = 1; at the bottom.c = 1; and change the 2 in char a = 2; to 300.c was never declared, so it’s rejected. Variables have to be declared first so the compiler can set aside a slot for each.
The demo’s instructions STORE to memory every time a value is set and LOAD it every time it’s read. An example this small could live in registers alone, but to keep things simple we always keep variables in memory for now. Ways to go to memory less often come later.
Put 300 into a and you get 44. In binary 300 is 1 00101100, 9 bits, so the top
1 doesn’t fit in one slot and is dropped, leaving the lower 8 bits 00101100,
which is 44.
Bigger numbers go into a short. A short joins two slots, 16 bits, and holds
−32768 to 32767. A short is 2 bytes both on our machine and on today’s
computers.
For short a = 300; the compiler sets aside two slots, labels the first a, and
calls the second a+1. What value should go into each slot?
In 16 bits 300 is 00000001 00101100, so it splits into an upper 8 bits of 1
and a lower 8 bits of 44. Now we have to decide which one goes at the lower
address.
Putting the low-order byte first is called little endian, and putting the high-order byte first is big endian. Our machine is little endian, and so are most CPUs in today’s PCs and smartphones (x86, ARM). So a gets 44 and a+1 gets 1. The compiler puts 44 in R0 and 1 in R1 and stores twice.
What instructions does adding two shorts, as in short c = a + b;, become?
We’ll see in the next post.
Inside main, you make variables by writing only lines that put 1 into a new variable: short x0 = 1;, short x1 = 1;, short x2 = 1;, … The compiler in this post adds HALT at the end and puts the variable slots after the program. At most how many variables can you make this way in 256 slots of memory? Answer with a number.