CS 330 Lecture 9 – C as Assembly++
Agenda
- the good and the bad of assembly
- two purposes for high-level languages
- hello, C
- primitive types in C
- checking the assembly with objdump
- strings in C
- the separation of definitions from declarations
- enums in C
- enums in Java
TODO
- If you want some refresher on types and C-style flow control, read the first two chapters of Nick Parlante’s Essential C. Most of the material is not that different from Java. Feel free to skip this.
- Read chapter 3 through section 3.2.2 (8 pages) and chapter 7 through section 7.1.4 (12 pages). Quarter sheet.
Outlook
- M: introduction, primitive types, strings, enums
- W: structs, call by value, pointers, dynamic allocation
- F: data structures without classes, makefiles
- M: functions as variables
- W: bit manipulation in marching squares
Code
our_first_c_program.c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
/*
char (1 byte), int, short, long
float double
*/
printf("sizeof char: %d\n", sizeof(char));
printf("sizeof short: %d\n", sizeof(short));
printf("sizeof int: %d\n", sizeof(int));
printf("sizeof long: %d\n", sizeof(long));
printf("sizeof long long: %d\n", sizeof(long long));
printf("sizeof unsigned char: %d\n", sizeof(unsigned char));
printf("sizeof unsigned short: %d\n", sizeof(unsigned short));
printf("sizeof unsigned int: %d\n", sizeof(unsigned int));
printf("sizeof unsigned long: %d\n", sizeof(unsigned long));
printf("sizeof unsigned long long: %d\n", sizeof(unsigned long long));
printf("sizeof float: %d\n", sizeof(float));
printf("sizeof double: %d\n", sizeof(double));
return 0;
}
string_test.c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
char numberish[] = "9509";
/* char numberish[] = { */
/* '9', */
/* '5', */
/* '0', */
/* '9', */
/* '\0' */
/* }; */
int n = 0;
for (int i = 0; numberish[i] != '\0'; ++i) {
n = n * 10 + (numberish[i] - '0');
}
printf("n: %d\n", n);
printf("n + 1: %d\n", n + 1);
return 0;
}
cards.c
#include <stdio.h>
#include <stdlib.h>
enum rank_t {
ACE = 1,
DEUCE,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
TEN,
JACK,
QUEEN,
KING
};
int main(int argc, char **argv) {
enum rank_t card1 = SEVEN;
enum rank_t card2 = JACK;
int ncards = 3;
enum rank_t hand[] = {
/* 42, */
ACE,
JACK,
ACE
};
int naces = 0;
int score = 0;
// Add up all the non-ACE cards first...
for (int i = 0; i < ncards; ++i) {
if (hand[i] == ACE) {
++naces;
} else if (hand[i] == KING || hand[i] == QUEEN || hand[i] == JACK) {
score += 10;
} else {
score += hand[i];
}
}
// See if adding one "power ace" on would shoot us past 21. If not, let's
// power up that ace to 11 and treat all others as 1. Otherwise, treat all
// aces as 1.
if (score + 11 + (naces - 1) <= 21) {
score += 11 + (naces - 1);
} else {
score += naces;
}
printf("score: %d\n", score);
return 0;
}
Haiku
my wife’s plan
Even so, I’m her type
enum husband_t
{FARMER, PASTOR, NATURE_BOY}
Even so, I’m her type