CS 11 C track: lecture 1
Preliminaries
n
Need a CS (CMS) cluster account
n
http://www.cs.caltech.edu/ cgi-bin/sysadmin/account_request.cgi ITS tutorial linked from track home page www.cs.caltech.edu/courses/cs11/material/c/mike
Need to know UNIX
n
Track home page:
n
Assignments
n
1st assignment is posted now Due one week after class, midnight Grading policy: see "admin page" linked from track home page
Other administrative stuff
n
Again, see admin web page:
http://www.cs.caltech.edu/courses/cs11/material/ c/mike/admin.html
n
Covers how to submit labs, collaboration policy, grading, etc.
Main textbook
n
C: A Software Engineering Approach, 3rd ed. by Peter A. Darnell, Philip E. Margolis Thorough, readable
Supplemental textbook
n
Kernighan and Ritchie:
1st edition NOT acceptable "ANSI C" Good for reference
The C Programming Language, 2nd. ed.
n n n
C: pros and cons
n
What C is good at
n n n
low-level programming speed and memory efficiency portability (sorta) unsafe!!! low level of abstraction
Bad things about C
n n
Getting started (1)
n
The "hello, world!" program:
#include <stdio.h> int main(void) { printf("hello, world!\n"); return 0; }
Getting started (2)
n
Make this into a file called hello.c using a text editor
n
e.g. emacs, vi, nedit, pico
Compile into a program and run:
% gcc hello.c -o hello % hello hello, world! %
Woo hoo!
Source code to executable (1)
n n
What you write is called "source code" Two kinds of source code files:
n n
regular code (files end in ".c") header files (files end in ".h") (files end in ".o")
Compiler turns source code into "object code"
n
Linker turns object code file(s) into executable (no special file suffix)
Source code to executable (2)
n n
The program gcc is both a compiler and a linker When you do this: % gcc hello.c -o hello Then gcc
n n n n
compiles hello.c to hello.o links hello.o with system libraries outputs the binary executable program hello removes hello.o
Source code to executable (3)
n
You can do each step individually:
% gcc -c hello.c % gcc hello.o -o hello (compile only) (link only)
n n
In this case, hello.o is not removed Sequence:
n n
compiling: source code to object code linking: object code to binary executable
The C language - overview
n n
Programs are built up of functions Functions
n n n
take in arguments compute something return a result
The main() function
n
is where program execution starts
Data types (1)
n n
All data in C has to have a specified type Examples:
n n n n
int char float or double others
(integer) (character) (approximate real number)
n n
Variables hold data of a particular type only Variables must be declared before use
Data types (2)
n
Type declarations:
int i; char c; double d; float some_float = 3.14; /* name = i /* name = c type = int */ type = char */
n n n
Identifiers: i, c, d, some_float Optional initialization (e.g. some_float) Booleans 0 or nonzero (usually 1)
Data types (3)
n
Strings: arrays of type char
char some_string[9] = "woo hoo!"; char same_string[] = "woo hoo!"; char *same_again = "woo hoo!";
n n
Much more on strings, arrays later Other types: structs, pointers
Operators (1)
n n
Numeric: + - * / % Assignment: = int i = 10; int j = 20; j = j % 2; /* initialization */ /* initialization */ */ */ /* assignment
i = 2 + i * j; /* assignment
Assignment operator
n
Assignment works this way:
n
1) Evaluate the right-hand side (RHS) of the assignment operator 2) Assign the resulting value to the lefthand-side (LHS) of the assignment operator
Operators (2)
n
What does
i = 2 + i * j;
mean?
a) i = (2 + i) * j; b) i = 2 + (i * j);
n n
* has a higher precedence than + Use () to force other interpretation
Operators (3)
n
Other assignment operators:
n
+=, -=, *=, ... /* i = i + 2; */ increment and decrement: ++, -/* i = i + 1; */ /* same */
i += 2;
n
i++; ++i;
Operators (4)
n
Test operators:
n n n
compare two values < <= > >= == for testing equality != for testing inequality read "!" as "not"
Operators (5)
n
Logical operators:
n
arguments are ints used as booleans i.e. usually 0 or 1 (false or true) ! operator is unary logical "not" && operator is binary logical "and" || operator is binary logical "or"
Operators (6)
int bool1, bool2, bool3, bool4; bool1 = 0; /* false */ /* bool2 --> true */ /* value? */ /* value? */
bool2 = !bool1;
bool3 = bool1 || bool2; bool4 = bool1 && bool2;
Operators (7)
n
"Unary minus" operator:
int var1 = 10; int var2; var2 = -var1;
n n
Like with nothing to the left Negates the value
Expressions and statements
n n
i + 2 * j is an expression (has a value) i = j * k; is a statement
n
ends in a semicolon also is an expression (value is value of i)
n n n
i = j = k = 0; is allowed Equivalent to i = (j = (k = 0)); NOT ((i = j) = k) = 0;
Comments
/* This is a comment. */ /* * Comments can span * multiple lines. */ // This is NOT a comment!
Functions (1)
n
Functions take arguments and return values:
int f(int x) { int y = 10; return y * x; }
Functions (2)
n
Functions take arguments and return values:
name
int f(int x) { int y = 10; return y * x; }
Functions (3)
n
Functions take arguments and return values:
argument list
int f(int x) { int y = 10; return y * x; }
Functions (4)
n
Functions take arguments and return values:
return type
int f(int x) { int y = 10; return y * x; }
Functions (5)
n
Functions take arguments and return values:
body
int f(int x) { int y = 10; return y * x; }
Functions (6)
n
Functions take arguments and return values:
int f(int x) { int y = 10; return y * x; }
return statement
Functions (7)
n
Calling the function we just defined:
/* in another function... */ int res; int i = 10; res = f(10); res = f(5 + 5); res = f(i); res = f(i*5 + i/2);
n n
All of these are valid function calls Take in arguments, return result
Functions (8)
n
Functions can take multiple arguments:
argument list
int g(int x, int y) { int z = 42; return x * y * z; }
n n
Argument names (x, y) preceded by type (int) Arguments separated by commas
Functions (9)
n
Calling functions that take multiple arguments:
/* in another function... */ int res; int i = 10, j = 20; res = g(10, 20); res = g(5 + 5, 20); res = g(i, j); res = g(i*5 + i/2, j * 10);
Functions (10)
n
Not all functions return values:
void print_number(int i) { printf("number is: %d\n", i); }
n n
Return type is void (nothing to return) Use this when no return value needed
Functions (11)
n
Not all functions return values:
void print_number(int i) { printf("number is: %d\n", i); return; /* unnecessary */ } n return statement not required
n
unless you return in the middle of the function
Functions (12)
n
Calling this function:
/* In another function... */ int i = 10; print_number(20); print_number(i); print_number(i*5 + i/2);
n
Prints 20, 10, 55 respectively
Functions (13)
n
Not all functions take arguments:
int five(void) { return 5; }
n
No arguments (use void to indicate)
Functions (14)
Calling functions without arguments: int value; value = five();
n n n
Now value equals 5 Note () after five
n
means "this function is being called with no arguments" Without this, function won't be called!
Functions type declarations
Type declarations, if needed, come at the beginning of the function n Need a declaration for every local variable int foo(int x) { int y; /* type declaration */ y = x * 2; return y; }
n
Functions type declarations
n
This is wrong:
int foo(int x) { int y; /* type decl */ y = x * 2; /* code */ /* type declaration after code: */ int z = y * y; return z; }
n
Generates a compiler warning
Local and global variables (1)
n n n
Variable declarations can be local or global Local: inside a function Global: outside a function
n
accessible from any function
Local and global variables (2)
int x; int y = 10; /* Global variable */ /* Initialized global variable */
int foo(int z) { int w; /* local variable */ x = 42; /* assign to a global variable */ w = 10; /* assign to a local variable */ return (x + y + z + w); }
Local and global variables (3)
n n
In general, avoid using global variables! Global variables can be changed by any function
n
makes debugging much harder though sometimes convenient
Global variables are never necessary
n
OK to use global "variables" if they really are constant
n
i.e. if you don't change their values
printf()
int a = 5; double pi = 3.14159; char s[] = "I am a string!"; printf("a = %d, pi = %f, s = %s\n", a, pi, s);
n n n
Substitutes values for %d, %f, %s etc. %d : int, %f : float, double, %s : string \n : new line
The C preprocessor (1)
n
What does the funky line #include <stdio.h> mean? C preprocessor directive Extra step in compilation:
n n n n
n n
cpp: source code -> expanded source code gcc: compiles source code -> object code gcc (ld): links object code -> executable gcc does all this for you
The C preprocessor (2)
n
What does the funky line #include <stdio.h> mean? Includes the declaration of printf()
n n
NOT the implementation allows your code to use printf()
The linker adds in the implementation
Conditionals (1)
n
Need to be able to test for conditions:
int a = 10; if (a < 20) { printf("less than 20\n"); } else { printf("not less than 20\n"); }
Conditionals (2)
n
Test: 0 is false, anything else is true:
if (1) /* true */ { printf("less than 20\n"); } else { printf("not less than 20\n"); }
Conditionals (3)
VERY common error: int a = 0; if (a = 10) /* always true! */ { printf("a equals 10\n"); } else { printf("a doesnt equal 10\n"); }
n
Conditionals (4)
Should be: int a = 0; if (a == 10) /* not always true */ { printf("a equals 10\n"); } else { printf("a doesnt equal 10\n"); }
n
Conditionals (5)
n
else clause is optional:
int a = 0; if (a == 10) { printf("a equals 10\n"); }
Conditionals (5)
n
else if for multiple cases:
int a = 0; if (a == 10) { printf("a equals 10\n"); } else if (a < 10) { printf("a is less than 10\n"); } else { printf("a is greater than 10\n");
for loop (1)
n
Need to do things repeatedly:
int i; for (i = 0; i < 10; i++) { printf("cowabunga!!!\n"); }
for loop (2)
for (<initialization>; <test>; <increment>) { <body> } for (i = 0; i < 10; i++) { printf("cowabunga!!!\n"); }
for loop (3)
for (<initialization>; <test>; <increment>) { <body> } for (i = 0; i < 10; i++) { printf("cowabunga!!!\n"); }
for loop (4)
for (<initialization>; <test>; <increment>) { <body> } for (i = 0; i < 10; i++) { printf("cowabunga!!!\n"); }
for loop (5)
for (<initialization>; <test>; <increment>) { <body> } for (i = 0; i < 10; i++) { printf("cowabunga!!!\n"); }
for loop (6)
for (<initialization>; <test>; <increment>) { <body> } for (i = 0; i < 10; i++) { printf("cowabunga!!!\n"); }
Thats all for now!
n
Much more on all these topics in later lectures Do first assignment to get familiar with basics Use "style checker" to avoid style mistakes Have fun!