1.38k likes | 1.93k Views
The C Programming Language. Currently one of the most commonly-used programming languages “High-level assembly” Small but powerful Very portable:compiler exists for virtually every processor. Hello World in C. Include a header file that lets you use I/O related C functions
E N D
The C Programming Language • Currently one of the most commonly-used programming languages • “High-level assembly” • Small but powerful • Very portable:compiler exists for virtually every processor
Hello World in C Include a header file that lets you use I/O related C functions Similar to Java’s import #include <stdio.h> int main() { printf(“Hello, world!\n”); return 0; }
Why is C Dangerous • C’s small feature set is an advantage and disadvantage • The price of C’s flexibility • C does not, in general, try to protect a programmer from his/her mistakes
Commonly used header files • stdio.h • Standard C library for I/O • stdlib.h • General purpose standard C library • string.h • math.h • sqrt, pow, sin, cos • ctype.h • a bunch of very useful character functions: isdigit,isalpha, isalnum, isspace, islower, isupper, tolower/toupper • time.h
Hello World in C Program mostly a collection of functions “main” function special: the entry point “int” qualifier indicates function returns an integer #include <stdio.h> int main() { printf(“Hello, world!\n”); return 0; } I/O performed by a library function
C is Function-oriented • C came before OO concept • C program resemble java programs with a single giant class • C is procedural • Program organization and modularization is achieved through function design • Carefully plan your function return type and parameter list • Write small functions!
Functions • Function: Unit of operation • A series of statements grouped together • Must have the main function • C functions are stand-alone • Most programs contain multiple function definitions • Must be declared/defined before being used
Functions int menuChoice() { int choice; printf( "1. Yes\n" "0. No\n" "Enter the number corresponding to your choice: "); scanf("%d", &choice); return choice; } int main() { int choice; printf("=== Expert System ===\n"); printf("Question1: ...\n"); choice = menuChoice(); if (choice == 1) { /* yes */ printf("Question 2: ...\n"); choice = menuChoice(); /* skipped */
Function parameters void km_mile_conv(int choice) { int input; printf("Enter a %s value: ", choice==1?"mile":"km"); scanf("%lf", &input); if (choice == 1) printf("%f mile(s) = %f km(s)\n", input, input*1.6); else printf("%f km(s) = %f mile(s)\n", input, input/1.6); } int main() { int choice; scanf("%d", &choice); switch (choice) { case 1: km_mile_conv(choice); break; caea 2: km_mile_conv(choice); break; /* more cases */ } }
Function Return and Parameters • The syntax for C functions is the same as Java methods • void keyword can be omitted void km_to_mile(void) { } mile_to_km() { } int main() { int choice; }
/* function prototypes */ double km2mile(double); double mile2km(double); int main() { } /* actual function definitions */ double km2mile(double k) { } double mile2km(double m) { } Function Prototype • A prototype is a function declaration which includes the returntype and a list ofparameters • A way to move function definitions after main • Need not name formal parameters
Function name overloading • Does not exist in C • Exists in C++
Local/Global Variables • Variables declared inside a function are local • Function arguments are local to the function passed to • A global variable is a variable declared outside of any function. • In a name conflict, the local variable takes precedence • When local variable shadows function parameter? int x = 0; int f(int x) { int x = 1; return x; } int main() { int x; x = f(2); }
Scope of Global Variables • The scope of a global variable starts at the point of its definition. • Globals should be used with caution • If using globals at all, declare them at the top. int x; int f() { } int y; int g(){ } int main() { }
Keep main Uncluttered • Your main function should consist mainly of function calls • One main input loop or conditional is okay • Write your main and choose your function name in such a way so that • the main algorithm and program structure is clearly represented • the reader can get an idea how your program works simply by glancing at your main
Program Organization • #include and #define first • Globals if any • Function prototypes, unless included with header file already • int main()– putting your main before all other functions makes it easier to read • The rest of your function definitions
Data Types • Integer types: • different number of bits-different ranges • char:ASCII character, typically 8 bits=1 byte • range –127 to 128 • short: typically 16 bits • int: 32 bits • range ±2 billion • long: typically 32 bits • long long: (some compilers support) 64-bits • Integer types can be preceded by unsigned which disables representing negative numbers • e.g. unsigned char • range 0-255
Data Types Floating-point types • float 4 bytes • double 8 bytes • long double 12 bytes • Floating point constants default to double unless suffixed by f or l • Examples: 0.67f, 123.45f, 1.2E-6f, 0.67, 123.45
Boolean • C does not have type boolean—use int • False is represented by 0 • Any expression evaluates to non-zero is considered true • True is typically represented by 1 however
Constants • Integer • const int year = 2002; • Floating point number • const double pi = 3.14159265; • Constants are variables whose initial value can not be changed. • Comparable to static final
#define • Often used to define constants • #define TRUE 1 #define FALSE 0 • #define PI 3.14 • #define SIZE 20 • Anywhere PI occurs compiler replaces with 3.14 • Offers easy one-touch change of scale/size • #define vs const • The preprocessor directive uses no memory
Types and Casting • Choose types carefully • An arithmetic operation requires that the two values are of the same type • For an expression that involves two different types, the compiler will cast the smaller type to the larger type • Example: 4 * 1.5 = 6.0
Mixing Data Types • int values only int • 4 / 2 2 • 3 / 2 1 • int x = 3, y = 2; x / y 1 • Involving a double value double • 3.0 / 2 1.5
sizeof and Type Conversions • sizeof(type) • The sizeof operator returns the number of bytes required to store the given type Implicit conversions • arithmetic • assignment • function parameters • function return type Explicit conversions • casting int x; x = (int) 4.0;
Use of char (character) • Basic operations • Declaration: char c; • Assignment: c = 'a'; • Reference: c = c + 1; • Constants • Single-quoted character (only one) • Some special characters: '\n‘ (newline), '\t' (tab), '\"' (double quote), '\'' (single quote), '\\' (backslash)
Characters are Integers • A char type represents an integer value • A single quoted character is called a “character constant”. • C characters use ASCII representation: • 'A' = 65 … 'Z' = 'A' + 25 = 90 • 'a' = 97 … 'z' = 'a' + 25 = 122 • '0'!= 0 (48),'9' - '0' = 9 • Never make assumptions of char values • Always write 'A' instead of 65
ASCII Table American Standard Code for Information Interchange A standard way of representing the alphabet, numbers, and symbols (in computers)
Output: Value = 100 Output Functions • Output characters printf("Text message\n"); • Output an integer int x = 100; printf("Value = %d\n", x); \n for new line
Output: x = 100, y = 1.230000 Variations • Output a floating-point number double y = 1.23; printf("Value = %f\n", y); • Output multiple numbers int x = 100; double y = 1.23; printf("x = %d, y = %f\n", x, y); 15 digits below decimal (excluding trailing 0’s)
printf Summary printf(" ", ); • Text containing special symbols • %d for an integer • %f for a floating-point number • \n for a newline • List of variables (or expressions) • In the order correspoding to the % sequence
% Specification • (most commonly used ones) • %c convert an int to an unsigned char and print as a character • %iint, char(printas a signed decimal number) • %d same as above (d for decimal) • %ffloat,double(floating-point) • %efloat,double(exponential, e.g., 1.5e3) • %sstring pointed by a char*
Formatting • Precision %.#f • Width %#f, %#d • Note: Entire width • Various combinations of the above and other options available Replace # with digit(s)
Formatting Example %f with 1.23456789 >1.234568< %.10f with 1.23456789 >1.2345678900< %.2f with 1.23456789 >1.23< %d with 12345 >12345< %10d with 12345 > 12345< %2d with 12345 >12345< %f with 1.23456789 >1.234568< %8.2f with 1.23456789 > 1.23<
char Input/Output • Input • char getchar() receives/returns a character • Built-in function • Output • printf with %c specification • putchar() int main() { char c; c = getchar(); printf("Character >%c< has the value %d.\n", c, c); return 0; }
scanf Function scanf(" ", ); • Format string containing special symbols • %d for int • %f for float • %lf for double • %c for char • \n for a newline • List of variables (or expressions) • In the order correspoding to the % sequence
scanf Function • The function scanf is the input analog of printf • Each variable in the list MUST be prefixed with an &. • Ignores white spaces unless format string contains %c
scanf Function int main() { int x; printf("Enter a value:\n"); scanf("%d", &x); printf("The value is %d.\n", x); return 0; }
scanf with multiple variables int main() { int x; char c; printf("Enter an int and a char:"); scanf("%d %c", &x, &c); printf("The values are %d, %c.\n", x, c); return 0; }
Control Structures • Conditionals • if-else • switch • Loops • while • for • do-while • SAME syntax as in Java
Assignment as Expression • Assignment • Assignments are expressions • Evaluates to value being assigned • Example int x = 1, y = 2, z = 3; x = (y = z); 3 3 3 evaluates to 3 (true) if (x = 3) { ... } evaluates to 3
Complex Data Types • Pointers • Arrays • Strings • Structures
Memory 0 1 2 3 4 5 6 7 8 9 30 31 70 31 4 6 30 1 10 4 6 95 201 12 address value Variable and Address • Variable = Storage in computer memory • Contains some value • Must reside at a specific location called address • Basic unit – byte • Imagine memory as a one-dimensional array with addresses as byte indices • A variable consists of one or more bytes, depending on its type (size) char int
Pointer – Reference • A pointer (pointer variable) is a variable that stores an address (like Java reference) • Recall in Java, when one declares variables of a class type, these are automatically references. • In C, pointers have special syntax and much greater flexibility.
Address Operations in C • Declaration of pointer variables • The pointer declarator ‘*’ • Use of pointers • The address of operator ‘&’ • The indirection operator ‘*’ – also known as de-referencing a pointer
ptr1 ptr2 Pointer Declaration • Syntax • destinationType*varName; • Must be declared with its associated type. • Examples • int *ptr1; A pointer to an int variable • char *ptr2; A pointer to a char variable will contain addresses
Pointers are NOT integers • Although memory addresses are essentially very large integers, pointers and integers are not interchangeable. • Pointers are not of the same type • A pointer’s type depends on what it points to • int *p1; • char *p2;
Address of operator 0012FF88 8 ip i (@0012FF88) int i = 8; int *ip; ip = &i;
1 x 567 567 p q 1 p q x Pointer Assignment • A pointer ppointsto x if x’s address is stored in p • Example • int x = 1; int *p, *q; p = &x; q = p; Interpreted as: address = 567
2 1 y x p q Pointer Assignment • Example • int x=1, y=2, *p, *q; p = &x; q = &y; q = p; address = 567 address = 988 567 567 988
1 x p Indirection Operator Note: ‘*’ in a declaration and ‘*’ in an expression are different. int *p; int * p; int* p; • Syntax • *pointerVar • Allows access to value of memory being pointed to • Also called dereferencing • Example • int x = 1, *p; p = &x; printf("%d\n", *p); *p refers to x; thus prints 1