2014-10-10 Part 0 - Intro -------------- We're going to look at writing a class-based software architecture in C, in particular, translating a Java program to C. Why? 0. When you're designing software, it can be useful to start with an abstract, language-indepdendent structure, e.g., classes. You then do the best you can in the language you have. 1. "Translating Java to C" is going to reinforce exactly what the C semantics are. If all you see is C used in the conventional way, it's hard to understand the distinction between semantics and convention. 2. C++ is a big language. The technique we'll use to translate Java to C is very close to what C++ does -- it's exactly what it did in the very early days of C++. (So, this exercise is preparation for C++.) Languages do at least three things: 0. Relieve the programmer of drudgery. 1. Check that the programmer has done some things right. 2. Make it hard for the programmer to do things wrong. You can think of C as a successor to assembly language. - The abstract machine assembler presents is the hardware. - The abstract machine C presents is barely more than the hardware. What is the compiler doing for you when you write this C? int sub(int x, int y) { return x+y; } drugery: - don't have to say .text, .global sub, .type sub, @function - don't have to compute stack offsets for x and y - don't have to write multi-instruction procedure entry/exit code sequences - don't have to keep track of whether x is in a register or in memory check that you've done things right: - compiler will complain if the value you return isn't an int (or can't be converted naturally to an int) make it hard to do things wrong: - compiler will complain if you forget to return a value Part 1 - Translating App/Point/Vector.java to C ----------------------------------------------- Imagine we want to write a 2D game engine. We'll want to provide a library that lets you create sprites, move them around, perform collision detection, and the like. Abstractly, we're talking about a package of that magnitude. Concretely, we look at a tiny bit of Java code that does hardly anything. Programming with classes: - want to be able to create new instances of Points and Vectors - want to invoke operations on those instances, and have compiler check that the operation is defined for members of that class - we'd like effective type checking -- e.g., can't pass in a Point when a Vector is required - [potentially want information hiding] - [potentially want inheritance]