Академический Документы
Профессиональный Документы
Культура Документы
• C Program Structure
• Program Elements
• Control Structures
• Structures, Union
Programming Process
+ documentation
Example
Hard problem
Easy Easy
subproblem subproblem
Structure of a C Program
The Greeting Program
Program Elements Lexical Tokens
• Character Set
• Keywords
• Identifiers
• Constants
• Literal Strings
• Operators
• Punctuators
• Special
Characters
C++ C
Identifiers
• Identifiers in C consist of three types:
– Reserved words (Keywords )
– Standard identifiers Not recommend to use for Programmer variables
– Programmer-created identifiers
• Can be any combination of letters, digits, or underscores (_)
subject to the following rules :
– First character must be a letter or underscore (_)
– Only letters, digits, or underscores may follow the initial character
– Blank spaces are not allowed
– Cannot be a reserved word
Keywords
Category Keyword
1.
int x = -10;
printf("%c\n", '1' + 1);
printf("%d\n", ~x+1);
2.
int sum = 5;
sum = sum + sum *5/2;
8 How does one indicate that certain text is to be treated as a "comment" in the
classic C language?
a. Place the text between /* */ .
b. Place 'COMMENT:' before the text.
c. Place '#' before the text.
d. Place the text between # and #.
L-value: An expression that refers to a region of storage; only l-values can be used at the
left side of “=” operator
if (x <= 10)
10) {
y = x*x + 5; X = 20;
z = (2
(2 * y) / 3;
}
Did you know that the following if statement is semantically right, but
could logically be wrong? if ( i = 2 ) { /* do something */ } Tip: The
compiler may only produce a waring: "Possibly incorrect assignment", but
we may ignore it. To avoid such a mistake, just reverse the two
identifiers. if ( 2 == i ) { /* do something */ } If '==' is replaced by an '=', the
compiler will give an error saying "Lvalue required".
if (n1 >= n2 >= n3) cout << "max = " << n1
The while loop
int oldval,newval = 0;
False
Test
int i;
True
for (i=0;i<10;i++){
oldval = newval; Body
newval = i; Re-init
}
printf("%d",oldval);
Write a program
1. Test whether a particular bit of given number is ON or OFF
2. Set a particular Bit on in a given number
• Write a program
1. To count number of bits in a given number
2. to count 1 bit and 0 bit in a given number
3. To swap two variables
4. To check a variable is even or odd
Jump
goto label1;
:
:
label1:
Structured Programming
• Structured programming is a design discipline
in which the programmer:
(1) uses only high-level control structures
(2) avoids using the goto statement
General
a. Do not create big “C” files. Split files into smaller logical files.
b. Limit the size of each function. Functions should fit into single page
whenever possible.
c. Logical units within a block shall be separated by one blank line.
d. Three blank lines shall separate functions.
e. Avoid use of multiple returns from function. Multiple returns will
reduce the readability of the code.
f. Access to hardware should be abstracted to enable portability. Avoid
access of hardware/peripherals such as timers, DMA in the source
files directly. Create functions that perform hardware/peripherals
related operations and use these functions wherever needed.
g. All variables should be initialized before use.
h. As the stack size is limited, recursion should be avoided
Function Syntax
Parameter names can
be omitted from the
function prototype
• Function Prototype:
return_type function_name (type1 name1,
type2 name2, …,
typen namen) ;
#include <stdio.h>
int func (int n){
int f, I i;
f=1;
for(i=1; i<=;n;i++){
f *=i;
}
return f;
}
main(){
printf("%d\n",func(4));
}
• Type
Attributes of Identifiers • Visibility (Scope)
• Uniqueness (Linkage)
• Permanence (Duration)
• Storage Class
• Qualifier (Modifiability)
In the following program segment The use of external variables are illustrated
in the following 2-file C programs
… in file 1
void f1 (…) extern int xy;
{ extern long arr [ ];
… main ( )
} {
…
int a, b, c; }
void f2(…) void foo (int abc) { … }
{ long soo (void) { … }
…
} in file 2
int xy;
Variables a, b, and c are accessible to long arr [100];
function f2 but not f1.
Given the following,
1. An int variable with block scope and temporary storage
2. A constant character variable with block scope
3. A float local variable with permanent storage
4. A register int variable
5. A char pointer initialized with a null character
#include <stdio.h>
int main() {
int i; for (i=0; i<5; i++){
int x = 0;
static int y = 0;
printf("x=%d, y=%d\n", x++, y++);
}
return 0;
Identify the storage class, access type of each declaration in the
following code portion:
int i = 0;
static int x;
extern float y;
volatile int i;
int myFunction() {
int i, j;
extern float z;
register long s;
static int index;
const char str[] = "Warning message.";
...
}
Array
Array: a set of index and value
data structure
For each index, there is a value associated with
that index.
representation
implemented by using consecutive memory.
0 1 2 3 4 5 6 7 8 9
int arr[10]; 21
5
arr
arr[0]=5;
arr[7]=21;
arr[10]=3; Error!!!
An Example
#include <stdio.h>
What value is stored in marks[i] if
float dataarray[5]; the value -10 is entered?
float total = 0;
#define LIMIT 100
float avg;
int main() { main() {
• Initialization 1 2
– int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; 3 4
– Initializers grouped by row in braces
– If not enough, unspecified elements set to zero 1 0
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; 3 4
Pointers and Variables
int a = 5; 0x4343525 5
Adress Memory
b = a; 0x2343223 0x4353524
How about
b = & a[0]?? vs. b=a;??
Passing Arrays
• When an array is passed to • Because you can compile
a function, what is being functions separately, the compiler
passed is a pointer to the must be able to “know” about an
array array being passed in to a
function, so you must specify all
– In the formal parameter
(or most) of the definition:
list, you can either
specify the parameter as – The type and all dimensions
an array or a pointer except for the first
void f1(int*,int);
void f2(int*,int);
void(*p[2]) (int*,int);
main() {
void f1(int *x, int y){
int a=3,b=5;
int temp;
p[0]=f1;
temp = *x; *x= y; y = temp;
p[1]=f2;
}
p[0](&a,b);
void f2(int *x, int y){
printf(" %d %d \n",a,b);
int temp;
p[1](&a,b);
temp = *x ; *x =y ; y = temp;
printf("%d %d \n", a,b);
}
}
Stack vs. Heap
{
int i;
Heap (grows up)
char bVal;
Static Data
LCD_init();
LCD_PutString(greeting);
… Code
}
Low end
Two ways to get an int:
• On the Stack:
int main() {
int myInt; //declare an int on the stack
myInt = 5; //set the memory to five
return 0;
}
• On the Heap:
int main() {
int *myInt = malloc(sizeof(int));
//allocate mem. from heap
*myInt = 5; //set the memory to five
return 0;
}
String (Array of Char)
• In C, we can emulate string with an 1-D array of char terminated by NULL
character (‘\0’)
• C does not know where an array ends at run time – no boundary
checking
• All C library functions that use strings depend on the null character being
stored so that the end of the string can be detected
• Example: char str [10] = {'u', 'n', 'i', 'x', '\0'};
– Length of str is 4 (not 5, and not the declared size of the array)
a
H e l l o \0
?
What's happening in C?
a
H e l l o \0
b
w o r l d \0
What's happening in C?
a
H e l l o w o r l d \0
b
w o r l d \0
What's happening in C?
b
w o r l d \0
Hello world
Functions from string.h
int main() {
int array[10];
int* pntr = array;
for(int i=0; i < 10; i++) {
printf(“%d\n”, pntr[i]);
}
return 0;
}
• We can “increment” a pointer, which has the effect of making it point to the
next variable in a array.
• Instead of having an integer counter, we iterate through the array by moving
the pointer itself.
• The pointer is initialized in the for loop to the start of the array. Terminate
when we get the tenth index.
void*
int i = 10;
• A pointer to nothing??
void *p = &i; /* p holds address of int value i */
• NO!! A pointer to anything
int *ip = (int *)p; /* ip now holds that same address
int main() { */
char c; int j = * ((int *)p ); /* j contains the value of i */
int i;
float f;
void* ptnr;
pntr = &c; //OK
pntr = &i; //OK
pntr = &f; //OK
return 0;
}
In your code:
unsigned char variable;
Is replaced with:
u8 variable;
Function Pointers
#include <stdio.h>
static void function(int a) {
printf("function: %d\n", a);
}
static void caller(void (*func)(int), int p) {
(*func)(p);
}
int main(void) {
caller(function, 10); return 0;
}
float plus (float a, float b) { return a+b; }
float minus (float a, float b) { return a-b; }
float multiply (float a, float b) { return a*b; }
float divide (float a, float b) { return a/b; }
struct pair y;
y.number = 216;
y.grade = ‘A’;
• The size of a structure can be determined using sizeof operator
– e.g. sizeof(y);
sizeof(y); /*may be bigger than 5!! */
– Addresses are normally multiple of 4
Structures and Pointers
Easier-to-use
*p 216
notation
A
char g = (*p).grade;
g A
char g = p-
p->grade;
Dereferencing Fields
12 14 end
head 10
Example
struct pair{
int number;
char grade;
struct pair *next;
} x = {2160,’A’},y = {2150,’B’};
x y
216 A • 215 B •
0 0
x.next = &y;
x.next-
x.next->number will be 2150
Using the variable x, give definitions for the following:
a) An integer
b) A pointer to an integer
c) A pointer to a pointer to an integer
d) An array of 10 integers
e) An array of 10 pointers to integers
f) A pointer to an array of 10 integers
g) A pointer to a function that takes an integer as an argument
and returns an integer
h) An array of ten pointers to functions that take an integer
argument and return an integer
• volatile qualifier
– Variable may be altered outside program
– Variable not under control of program
– Variable cannot be optimized
int check_iobuf(void) {
int val;
*iobuf = 1;
while (*iobuf == 0) { }
val = *iobuf; *iobuf = 0; return(val); }
if iobuf had not been declared volatile, the compiler would notice that nothing
happens inside the loop and thus eliminate the loop
const and volatile can be used together
#define SQUARE(A) A * A
int func(int m) {
int i;
i = SQUARE(4+m);
return i;
}
C Example for Maintainability
enum Color {White, Green, Blue, Black};
main(){
enum Color x = Black;
int i = x;
while (i >= White){
if (i < Green)
printf(“this is a light color!\n”);
i--;
}
}
Evaluation of Enumeration Types
struct {
unsigned int baud : 5;
unsigned int div2 : 1;
unsigned int use_external_clock : 1;
} flags;
• Compiler will pack these fields into words
• Very implementation dependent: no guarantees of
ordering, packing, etc.
• Usually less efficient
– Reading a field requires masking and shifting
C Unions
• Can store objects of different types at different times
union {
int ival;
float fval;
char *sval;
};
struct node {
int value;
5
struct node *next;
};
Undefined pointer
The structure of a linked list
struct list {
int value;
struct list *next;
};
main(){
struct list n1, n2, n3,*l;
l= &n1;
n1.value = 100;
n2.value = 200;
n3.value = 300;
n1.next = &n2;
n2.next = &n3;
n3.next = NULL;
while(l) {
printf("%d\n", l->value);
l = l->next;
}
}
Deleting an entry from a linked list
Stack