Download presentation
Presentation is loading. Please wait.
Published bySuharto Yuwono Modified over 6 years ago
1
Variable Names Names are a sequence of visible characters
Must start with a non-numerical character int testvar1; OK int 1testvar; Illegal Cannot use C language keywords if, else, while, etc.
2
Types and Type Qualifiers
Several built-in types, different sizes Type Size Notes char 1 byte Fixed size int Typically, word size 16 bit minimum float Single-precision floating point 64 bits, typical double Double-precision floating point 64, 128 typical Type qualifiers exist: short, long Char is 8 bits on all platforms
3
Global Variables int global_i; void foo () { extern int global_i; A variable is global if it is defined outside of any function A global variable must declared as an extern in any function using it Extern not needed if global declaration is before the function Variables can be global across files
4
Constants Can use #define compiler directive #define ANSWER 42
Any instance of the string is substituted at compile time Character Constants Written as a single character in single quotes #define TERMINATOR ‘x’ Integer equal to the ASCII value of the character Some characters are not easy to represent (i.e. bell)
5
Character Arrays char type is used to describe ASCII characters
Each character has a unique 8-bit code A string is an array of chars Strings always need to end with a terminator character, ‘\0’ A printf displays all of memory until it sees a terminator Use of “” inserts terminator automatically Ex. “hello, world” has 13 characters 10 letters + 1 comma + 1 space + \0
6
Enumeration Constants
Describe variables with a fixed (relatively small) number of possible values Months could have 12 values Days could have 7 values enum bool_num { HIGH, LOW}; bool_num = HIGH; legal bool_num = 0; illegal
7
CONST Type Qualifier Declares that the variable should not be modified
const double pi = Undefined behavior if the variable is modified
8
Arithmetic/Relational Operators
+, -, *, / % is the modulo operator, division remainder Ex. 9 % 2 = 1, 9 % 3 = 0 ++ (increment) , -- (decrement) ==, <, >, <=, >=, != Ex. if (x < 5) …
9
Logical Operators && (AND), || (OR), ! (NOT)
Treat arguments as 1-bit binary values 0 is FALSE, not-0 is TRUE Ex. if ((A == 1) && !B)
10
Type Conversions Variables of one type can be treated as another type
char could be treated as an int Sizes can be increased automatically 8-bit char to 32 bit int, sign extension char c; c = c – (‘A’ – ‘a’); ‘A’ – ‘a’ Difference between capitals and lower case
11
Type Casts Type conversions can be forced by the programmer
float c; printf (“%i”, (int) c); Needed to convert a small type to a larger type int x; sqrt((double) x);
12
Increment/Decrement ++ is increment, -- is decrement
Can act as a prefix or a suffix Prefix: increment then use Suffix: use then increment int i=0, x; x = i++; x = ++i;
13
Bitwise Operations Treat the value as an array of bits
Bitwise operations are performed on pairs of corresponding bits X = 0b0011, Y = 0b0110 Z = X | Y = 0b0111 Z = X & Y = 0b0001 Z = X ^ Y = 0b0101 Z = ~X = 0b1100 Z = X << 1 = 0b0110 Z = x >> 1 = 0b0001
14
Bit Masks Need to access a subset of the bits in a variable
Write or read Masks are bit sequences which identify the important bits with a ‘1’ value Ex. Set bits 2 and 4 in X, don’t change other bits X = , mask = X = X | mask Ex. Clear bits 2 and 4 mask = X = X & mask
15
Bit Assignment Macros #define SET_BIT(p,n) ((p) |= (1 << (n)))
#define CLR_BIT(p,n) ((p) &= ~(1 << (n))) 1 << (n) and ~(1) << (n) create the mask Single 1 (0) shifted n times Macro doesn’t require memory access (on stack)
16
Conditional Statements
if (expression) statement1 else statement2 if (expr1) stat1 else if (expr2) stat2 else stat3 else is optional expression is evaluated Execute statement1 if TRUE, statement2 if FALSE expr2 evaluated if expr1 is FALSE
17
Switch switch (expression) { case const_expr1: stat1
default: stat3 } expression is evaluated, compared to const_expr Statements are executed corresponding to the first matching expression
18
Break in a Switch switch (x) {
case 0: y = 1; case 1: y = 2; break; case 2: y = 3; } Without a break statement, the case will not end
19
While and For Loops for (expr1; expr2; expr3) statement expr1; do { statement expr3; } while (expr2); expr1; while (expr2) { statement expr3; } Initialization and increment are built into the for loop Condition checked at the top of a for/while loop Condition checked at the bottom of a do-while loop
20
Break and Continue Break jumps to the end of a for, while, do, or case
while (x > 5) { y++; if (y < 3) break; x++; } Continue jumps to the next iteration of a loop while (x > 5) { y++; if (y < 3) continue; x++; }
21
Problems with Break and Continue
Control-flow becomes convoluted while (x > 5) { y++; if (y < 3) continue; x++; } Rewrite the loop instead y++; while (x > 5){ if (y >= 3) x++; }
22
Gotos and Labels Control flow jumps to the indicated label
if (x > 5) goto dest; … dest: printf (“x > 5\n”); Never use this Control-flow becomes very convoluted Use a function call instead Control-flow will eventually return
23
Static Variables A static variable (or function) is visible only in one file extern will not make it visible Between a global and a local variable static char buf[BUFSIZE]; static int bufp = 0; Classes obviate the need for this Control access by passing an object as an argument
24
Register Variables Stored in registers, if there is space
Speeds access to data register int x; register char c; Useful if access pattern is dynamic for (i=0; i<x; i++) { val = … If you know that x is always large, place val in a register
25
Volatile Variables The value of a volatile variable may change at any time, not just at an explicit assignment Also, may be read at any time Compiler optimizations are not applied to volatile variables for (i=0; i<10000; i++); An optimizing compiler would delete this loop i is not used anywhere in the code i = 1; … i = 1; If i is not modified in between, the second assignment is removed
26
Volatile Variables When can variables be used without an explicit assignment? 1. Memory-mapped peripheral registers 2. Global variables modified by an interrupt service routine 3. Global variables accessed by other processors
27
Volatile Example periph is a register used to access a peripheral
Assigning periph=1 starts ADC Reading periph==1 indicates completion periph = 1; while (periph != 1); periph does not seem to be changed during each iteration Compiler would delete the entire loop
28
Recursion When a function calls itself
int fibonacci (int n) { if ((n == 0) || (n == 1)) return (1); return (fibonacci(n-1) + fibonacci (n-2)); } Maximum memory requirements are not known How many times will fibonacci be called? Usually can be avoided
29
Conditional Inclusion
Can compile conditionally based on a constant #if SYSTEM == UBUNTU #include “ubuntu.h” #elif SYSTEM == WINDOWS #include “win.h” #endif #ifdef DEBUG printf(“Debug msg\n”); Compilation depends on constants SYSTEM, DEBUG
30
Pointers A pointer is an address to data in memory
& operator returns the address of a variable/function * operator returns data at an address (dereferencing) int x = 1, y = 2, z[10]; int *ip; /* ip is a pointer to int */ ip = &x; /* ip now points to x */ y = *ip; /* y is now 1 */ *ip = 0; /* x is now 0 */ ip = &z[0]; /* ip now points to z[0] */ *ip is an alias for x, z[0]
31
Pointer Size Pointers are constrained to point to a single type
Except void * pointers Pointer size is independent of type size Pointer is 32-bits, typically Pointer arithmetic is possible Increments based on size of type *ip = *ip + 10; *ip++; (*ip)++; // NOT pointer arithmetic Arithmetic allows you to directly access memory Can view/modify arbitrary memory locations Debugging and security problems
32
Call by Reference Pointers may be passed as an argument to a function
Allows called function to modify variables of caller void swap(int x, int y) /* WRONG */ { int temp; temp = x; x = y; y = temp;} void swap(int *px, int *py){ int temp; temp = *px; *px = *py; *py = temp;}
33
Multiple Return Values
Functions can “return” more values by modifying referenced arguments void div(int x, int y, int *q, int *r){ *q = x / y; *r = x % y; return; } div (11, 5, ", &rem);
34
Arrays and Pointers An array is a sequence of data in memory
Array name is a pointer to the first element int a[10], *pa, *pan, x; pa = &a[0]; // pa points to the first elt pa = a; // pa points to the first elt pan = pa + 1; // pan points to the second elt x = *(pa + 1); // x is value of the second elt
35
Arrays as Arguments Passing an array name is the same as passing a pointer to the first element char s = “hello, world”; printf (“%i\n”, strlen(s)); int strlen(char s[]){ int n=0; while (s[n] != '\0') n++; return n; } int strlen(char *s){ int n; for (n = 0; *s != '\0‘; s++) n++; return n; }
36
Pointers and Allocation
Declaring a pointer only allocates space for the pointer Cannot access an uninitialized pointer char s[10]; char *ps; strncpy(s, “hello”, 6); // legal strncpy(ps, “hello”, 6); // illegal s points to a block of 10 memory locations ps points to nothing
37
Pointer Arrays An array can contain pointers
Useful to store and array of strings char *a = “I”, *b = “am”, *c = “hungry”; char *str_arr[3]; str_arr[0] = a; str_arr[1] = b; str_arr[2] = c;
38
Multidimensional Arrays
An array of arrays All subarrays are the same size // pop contains population on each block // 4 streets, 3 avenues int pop[4][3] = {{5,7,6}, {9,7,2}, {4,2,3}, {1,0,6}} Classes are more useful Names can be used for indexing
39
Command Line Arguments
Programs can be called with arguments % sum 2 3 5 Arguments are passed to main as an array of strings void main (int argc, char *argv[]) argc is number of args (+ program name) argv is the array containing each arg string argc = 3 argv[0] = “sum”, argv[1] = “2”, argv[2]=“3”
40
Function Pointers Can define pointers to functions, just like variables int addInt(int n, int m) { return n+m; } int (*functionPtr)(int,int); functionPtr = &addInt; int sum = (*functionPtr)(2, 3); // sum == 5 int add2to3(int (*functionPtr)(int, int)) { return (*functionPtr)(2, 3); } Arguments are passed to main as an array of strings
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.