C Language
C Language
C Language
Introduction to C
Writing C Programs
What is C?
Laboratories 1972
16-bit DEC PDP-11
computer (right) Widely used today extends to newer system architectures efciency/performance low-level access
Features of C
C features:
Few keywords Structures, unions compound data types Pointers memory, arrays External standard library I/O, other facilities Compiles to native code Macro preprocessor
Versions of C
specication of language
1989 C89 standard (known as ANSI C or Standard C) 1990 ANSI C adopted by ISO, known as C90
1999 C99 standard
mostly backward-compatible not completely implemented in many compilers 2007 work on new C standard C1X announced
Systems programming:
OSes, like Linux microcontrollers: automobiles and airplanes embedded processors: phones, portable electronics, etc. DSP processors: digital audio and TV systems
. . .
More recent derivatives: C++, Objective C, C# Inuenced: Java, Perl, Python (quite different) C lacks: exceptions range-checking garbage collection
object-oriented programming
polymorphism
. . .
Low-level language faster code (usually)
Inherently unsafe:
No range checking Limited type safety at compile time No type checking at runtime
Introduction to C
Writing C Programs
Editing C code
More later. . .
Compiling a program
gcc (included with most Linux distributions): compiler .o extension omitted for common programs like gcc
Run gcc: athena%1 gcc -Wall infilename.c -o outfilename.o -Wall enables most compiler warnings More complicated forms exist multiple source les auxiliary directories
optimization, linking
Embed debugging info and disable optimization: athena% gcc -g -O0 -Wall infilename.c -o outfilename.o
1 Athena is MIT's UNIX-based computing environment. OCW does not provide access to it.
Debugging
Using gdb
le
run run program
c continue execution
next execute next line step execute next line or step into function quit quit gdb print expression print current value of the specied
expression
help command in-program help
11
Memory debugging
13
Using Eclipse
http://www.eclipse.org/cdt/)
Use New > C Project choose Hello World ANSI C Project for simple project Linux GCC toolchain sets up gcc and gdb (must be installed separately) Recommended for nal project
14
Introduction to C
Writing C Programs
15
In style of Hello, world! .c le structure Syntax: comments, macros, basic declarations The main() function and function structure Expressions, order-of-operations Basic console I/O (puts(), etc.)
15
Structure of a .c le
/* Begin with comments about file contents */ Insert #include statements and preprocessor definitions Function prototypes and variable declarations Define main() function { Function body } Define other function { Function body } . . .
16
Comments
17
Header les: constants, functions, other declarations #include <stdio.h> read the contents of the header le
stdio.h
stdio.h: standard I/O functions for console, les
/ h e l l o . c our f i r s t C program Created by D a n i e l Weller , 01/11/2010 / # include < s t d i o . h> / b a s i c I /O f a c i l i t i e s /
18
stdio.h part of the C Standard Library other important header les: ctype.h, math.h, stdlib.h, string.h, time.h For the ugly details: visit http: //www.unix.org/single_unix_specification/ (registration required) Included les must be on include path -Idirectory with gcc: specify additional include directories standard include directories assumed by default #include "stdio.h" searches ./ for stdio.h rst
19
Declaring variables
int - integer data type float - oating-point data type Many other types (more next lecture. . . )
20
Initializing variables
Uninitialized, variable assumes a default value Variables initialized via assignment operator:
n = 3;
21
Arithmetic expressions
y = x+3x/(y4);
Numeric literals like 3 or 4 valid in expressions Semicolon ends statement (not newline) x += y, x -= y, x *= y, x /= y, x %= y: arithmetic
and assignment
22
Order of operations
Order of operations:
23
Order of operations
24
Order of operations
24
Order of operations
24
Order of operations
24
Order of operations
24
Order of operations
24
Function prototypes
Functions also must be declared before use Declaration called function prototype Function prototypes:
int factorial ( int );
or
C Standard Library
25
Function prototypes
General form:
return_type function_name(arg1,arg2,...);
Arguments: local variables, values passed from caller Return value: single value returned to caller when function
exits
void signies no return value/arguments
int rand(void);
26
main(): entry point for C program Simplest version: no inputs, outputs 0 when successful,
arguments
int main(int argc, char argv);
27
Function denitions
Function declaration { declare variables; program statements; } Must match prototype (if there is one)
variable names dont have to match
no semicolon at end Curly braces dene a block region of code Variables declared in a block exist only in that block Variable declarations before any other statements
28
/ The main ( ) f u n c t i o n / i n t main ( void ) / e n t r y p o i n t / { / w r i t e message t o console / p u t s ( "hello, 6.087 students" ) ; r e t u r n 0 ; / e x i t ( 0 => success ) / }
the line
String literal: written surrounded by double quotes return 0;
29
const keyword: qualies variable as constant char: data type representing a single character; written in
quotes: a, 3, n
const char msg[]: a constant array of characters
30
Strings stored as character array Null-terminated (last character in array is \0 null) Not written explicitly in string literals Special characters specied using \ (escape character): \\ backslash, \ apostrophe, \ quotation mark \b, \t, \r, \n backspace, tab, carriage return, linefeed \ooo, \xhh octal and hexadecimal ASCII character codes, e.g. \x41 A, \060 0
31
Console I/O
stdout, stdin: console output and input streams puts(string): print string to stdout putchar(char): print character to stdout char = getchar(): return character from stdin string = gets(string): read line from stdin into
string
Many others - later this week
32
Preprocessor macros
33
parentheses ensure order of operations compiler performs inline replacement; not suitable for
recursion
34
once
35
#pragma
preprocessor directive
#error, #warning
36
1 Athena is MIT's UNIX-based computing environment. OCW does not provide access to it.
37
Or, in gdb,
athena% gdb hello.o
.
. . Reading symbols from hello.o...done. (gdb) run Starting program: hello.o hello, 6.087 students Program exited normally.
(gdb) quit
athena%
Athena is MIT's UNIX-based computing environment. OCW does not provide access to it.
38
Summary
Topics covered:
How to edit, compile, and debug C programs C programming fundamentals:
comments
preprocessor macros, including #include the main() function declaring and initializing variables, scope using puts() calling a function and passing an argument returning from a function
39
For information about citing these materials or our Terms of Use,visit: http://ocw.mit.edu/terms.