Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

LO2 - Introduction To C Language

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 37

HCT

2.0

Introduction to
C Language

HCT – ELE-3614 - Microcontrollers


HCT
2.0

Outline
 Why C
 Structures (Records) and Type Definitions
 General Structure • Struct
• The “main” function • Typedef
 Constants • Union
• Numeric constants  Pointers
• Character constants • Variable address or pointer
• String constants • Array pointer
• The “#define” statement  Functions and Parameter Passing
 Variables • Void functions
• Character • Functions returning a value
• Integer • Parameter passing (by value)
• Real • Parameter passing (by reference);
 Function Pointers
 Operators  Libraries
• Arithmetic Operators • The “#include” statement
• Relational Operators
• Logical and Bitwise Operators
 Control Sequence Constructs
• If statement
• While statement
• For statement
• Switch statement

HCT – ELE-3614 - Microcontrollers 2


HCT
2.0

Why C
 It is a “mid-level” language that bridges the gap
between assembly and “high-level” languages.
Contains many of the both worlds features
 It is very efficient
 Good Compilers available for a wide range of
embedded processors
 Information and training are available in books and
the www.
 Easy to learn for experienced programmers (Java)

HCT – ELE-3614 - Microcontrollers 3


HCT
2.0

General Structure
All the components are functions (methods)
Functions are calling other functions
The starting point is a function always called “main”
int main() { void funct2 (p3) {
// This is a comment …
/* Another comment }
Put your code here
*/ int funct3 (p4) {
} …
}
void funct1(p1, p2, …) {

}

HCT – ELE-3614 - Microcontrollers 4


HCT
2.0

Constants
Numeric Constants
• Decimal: 1, 5, 27
• Hexadecimal: 0x07, 0xf8, 0x14
• Octal: 0o01, 0o016, 0o27
• Binary: 0b001010
• Floating Point: 1.27, 3.56e+16
Character Constants
• ‘c’, ‘d’, ‘3’, ‘@’
String Constants
• “Language”, “Embedded Systems”, “A Real 3-D System”

HCT – ELE-3614 - Microcontrollers 5


HCT
2.0

Predefined Constants
The #define statement:
//Defining constants(renaming constants)
#define ASIZE 5
#define PSIZE ASIZE+5
#define PARTSTR "ghtw_z0“

void f3() {

if(k < ASIZE) {

}
}

HCT – ELE-3614 - Microcontrollers 6


HCT
2.0

Variables
 Container in Memory that can be assigned a value.
 Has a predefined type
 Variables CANNOT change their type during
execution
 Variables have a unique identifier

n t i f i er
Ide 97

HCT – ELE-3614 - Microcontrollers 7


HCT
2.0

Built-in Data Types


// Strings and very short integer
char
unsigned char
// Integer
short (16-bits signed)
unsigned short
int
long
unsigned long
long long
// Floating point
float //single precision
double //double precision

HCT – ELE-3614 - Microcontrollers


HCT
2.0

Types Characteristics
Name Description Size* Range*
char Character or small 1 byte signed: -128 to 127
integer unsigned: 0 to 255
short int Short integer 2 bytes signed: -32768 to 32767
(short) unsigned: 0 to 65535
int Integer 4 bytes signed: -2147483648 to
2147483647
unsigned: 0 to 4294967295
long int Long integer 4 bytes signed: -2147483648 to
(long) 2147483647
unsigned: 0 to 4294967295
float Floating point number 4 bytes 3.4e +/- 38 (7 digits)

double Double precision 8 bytes 1.7e +/- 308 (15 digits)


floating point number
long double Long double precision 8 bytes 1.7e +/- 308 (15 digits)
floating point number

HCT – ELE-3614 - Microcontrollers


HCT
2.0

Variable Identifier
 First Character MUST be: _ , A-Z or a-z
 Remaining Characters MUST be: _ , A-Z, a-z, 0-9
 Cannot use any special character in the name like *, &, /
or ;
// Legal Identifiers
int _advance;
float Academic_rank;
char city01;

// Illegal Identifiers
double 0Arbitrary; // ‘0’ as first character
int Val*ue; // contains a ‘*’
char –Item; // ‘-’ is not ‘_’

HCT – ELE-3614 - Microcontrollers 10


HCT
2.0

Assigning Values to Variables


Putting a value into the container which label is specified in the variable name

Variable = Expression
Left Hand Side:Single Variable Name
Right Hand Side: Expression composed of variables, function calls and/or
operators

int a,b,c;
...
a = a * b + c/2;
b = (c + 5) % 3;

HCT – ELE-3614 - Microcontrollers


HCT
2.0

In C, all types are numbers


// Defining Variables
char c;

// Assigning values to variables


c = c+1;
...
c = 'v';
c = 0x78;
c = 67;
c = 2356; // after ex: c contains
// 0x34, because 2356 = 0x934

HCT – ELE-3614 - Microcontrollers


HCT
2.0

Arithmetic Operators
Operator Operation Example Result
+ Addition X+Y Sum of X and Y
- Subtraction X-Y Difference between X and Y
* Multiplication X*Y Product of X and Y
/ Division X/Y Quotient of X divided by Y
% Modulo X%Y Remainder of X divided by Y
- (unary) Negation -X Negation of X

 Division follows type.


 Division between integers will produce an integer
without a fraction
Ex: a = 10/3; // will produce 3 and not 3.33

HCT – ELE-3614 - Microcontrollers


HCT
2.0

Relational Operators
Operator Operation Example Result
< Less than X<Y True if X less than Y and false otherwise
<= Less than or X <= Y True is X less than or equal to Y and false
equal otherwise
> Greater than X>Y True if X greater than Y and false otherwise
>= Greater than or X >= Y True if X greater than or equal to Y and false
equal otherwise
== Equal X == Y True is X is equal to Y and false if X is
different than Y
!= Not Equal X != Y True is X is different from Y and false if X is
equal to Y

 Result of these expressions is logical ‘true’ or ‘false’


 The values ‘true’ and ‘false’ do not exist in C
 C considers that the value 0 is ‘false’ and any numerical value other than 0 is ‘true’

HCT – ELE-3614 - Microcontrollers


HCT
2.0

Logical and Bitwise Operators


Operator Operation Example Result
&& Logical AND (X > A) && Realizes a logical AND between two logical
(Y > B) expressions
|| Less than or (X > A) || Realizes a logical OR between two logical
equal (Y >= B) expressions
& Bitwise AND X&Y Bit by Bit AND operation between two
numbers
| Bitwise OR X|Y Bit by Bit OR operation between two
numbers
^ Bitwise XOR X^Y Bit by Bit XOR operation between two
numbers
~ Not ~X Inversion of every bit of a given number
>> Shift right X >> 3 Shift the contents of X to the right by 3-bits
<< Shift left X << A Shift the contents of Y to the left by A-bits

HCT – ELE-3614 - Microcontrollers


HCT
2.0

Precedence of Operators
Operator Operation Evaluation
() Parentheses Evaluated first. If nested pairs, the innermost pair is evaluated first. If
there are several pairs at the same level, they are evaluated from left
to right
!, - or + Logical Not, signs Evaluated second. If there are several, they are evaluated right to left
*, / or % Multiplication, Evaluated third. If there are several, they are evaluated left to right
Division, Modulus
+ or - Addition, Evaluated fourth. If there are several, they are evaluated left to right
Subtraction
>, <, >=, <= Relational Evaluated fifth. If there are several, they are evaluated left to right
Operators
==, != Equality Operators Evaluated sixth. If there are several, they are evaluated left to right
&& Logical AND Evaluated seventh. If there are several, they are evaluated left to right
|| Logical OR Evaluated eighth. If there are several, they are evaluated left to right

HCT – ELE-3614 - Microcontrollers


HCT
2.0

Short Form Assignments


Long Form Short Form
X = X + Y; X += Y;
X = X – Y; X -= Y;
X = X * Y; X *= Y;
X = X / Y; X /= Y;
X = X % Y; X %= Y;
X = X >> Y; X >>= Y;
X = X << Y; X <<= Y;
X = X & Y; X &= Y;
X = X | Y; X |= Y;

HCT – ELE-3614 - Microcontrollers


HCT
2.0

Increment/Decrement

Long Form Short Form Increment/Decrement


X = X + 1; X += 1; X++;
X = X – 1; X -= 1; X--;

Just a special case when Y=1.

HCT – ELE-3614 - Microcontrollers


HCT
2.0

Use of Operators
int a,b,c,i,j,k;
float m,n,p,q;

// Addition
a = b + 3;
b -= 5;

HCT – ELE-3614 - Microcontrollers


HCT
2.0

Arrays
// Defining Arrays:
int a[4]; // One dimension, 4 elements
// Index from 0 to 3
float k[2][15]; // Two dimensions 30 elements
// First dimension 2 “rows”
// Second dimension 15 elements
char buf[270];

// Array access
int i,j,k;
a[0] = a[i]; // i is an index-variable

k[i][k] = a[i*3+j] // index can be expression

HCT – ELE-3614 - Microcontrollers


HCT
2.0

Conversion and Casting


//About Casting and Conversion:
int k, v;
float w,m;

m = 1.75;
w = 2.35;
k = w; // fractional part truncated
k = (int) w; // same but safer to read

k = (int) (w / m); // k = 1; result of div = 1.34


v = ((int) w / (int) m); // k = 2

// Real  Integer: Loss of fractional part


// Integer  Real: No Loss

HCT – ELE-3614 - Microcontrollers


HCT
2.0

Control Sequences
 If statement
 While statement
 For statement
 Switch statement

HCT – ELE-3614 - Microcontrollers


HCT
2.0

If statement
if (k == 0) {
printf(“Main Operation\n”);
b = 1;
}
else {
k = 7;
b = 2;
}

 Classical representation of “if” statements where the


“else” statement is optional
 Nesting of “if” statements is allowed

HCT – ELE-3614 - Microcontrollers


HCT
2.0

While Loop
k = 1;
b = 0;
while ((k < 200) && (b == 0)) {
if( a[k] == 12)
b = 1;
else k++;
}
 While loops can be nested
 While loops body can contain any other statement.

HCT – ELE-3614 - Microcontrollers


HCT
2.0

For Loop
for (k = 0; k < 200; k++) {
if(a[k] == 12) break;
else continue;
}

 Classical “for” loop as in Java and other languages


 “break” and “continue” statements needed to either
exit from the loop or continue to the next index value

HCT – ELE-3614 - Microcontrollers


HCT
2.0

Switch  Classical “switch”


switch(k) {
case 0:
statement as in Java and
x = a[0]; some other languages
break;  “break” statement needed
case 1:
x = a[1]; to exit from the “switch”
break; structure
case 2:
case 3:  “case” statements that
x = a[2]; follow each other realize an
case 4: “or”.
case 5:
case 6: • For example case 2 and
x = a[3]; case 3 means:
break;
default: break; k == 2 or k == 3
}

HCT – ELE-3614 - Microcontrollers


HCT
2.0

User-Defined Structures
 A record type is defined by the  It can also be
“struct” constructor according defined all at once
to the following template: like:
struct MyRecord {
struct MyRecord {
int count;
int count;
char name[100];
char name[100];
int age;
int age;
}
} Var1;
 A Variable is declared as:
MyRecord Var1;

HCT – ELE-3614 - Microcontrollers


HCT
2.0

User-Defined Types
 Users can define types that will have a global scope
and can be used to dynamically allocate memory:

typedef struct MyNewType {


int value;
char flag;
struct MyRecord *record;
} MyNewTypeStr;

HCT – ELE-3614 - Microcontrollers


HCT
2.0

Accessing member fields


 Access member fields using the “dot” operator like
this:
struct MyRecord {
int count;
char name[100];
int age;
} Var1;
...
int k, m;
char *n1;
k = Var1.count;
n1 = Var1.name;
c = n1[20]; // 20th character of field name
m = Var1.age;

HCT – ELE-3614 - Microcontrollers


HCT
2.0

Pointers
 Variables are accessed by name or by “pointer”.
 Any built-in or user-defined type can have pointers.
A pointer type is defined as a container of the
address of a specific type:
• Example: integer pointer: int a, *p;
• Put address of a into p: p = (int *) &a;
 Array variables alone are of type pointer:
char name[100], *q, c;
q = name; c = *q; // access first character

HCT – ELE-3614 - Microcontrollers


HCT
2.0

Functions
 C structure uses functions as the sole container.
<return_type> <function_name> (<param_list>) {
<local variables definition>
<function body>
}

 A procedure (function that does not return anything)


is a function of return type “void”
void dowait() {
while(!done);
}

HCT – ELE-3614 - Microcontrollers


HCT
2.0

Functions
 A function that returns the maximum between two
numbers:
int max(int a, int b) {
if(a > b) return(a);
else return(b);
}
 A recursive function that computes aexp :
int power(int a, int exp) {
if(exp == 0) return(1);
else return(a*power(a, exp-1));
}

HCT – ELE-3614 - Microcontrollers


HCT
2.0

Parameters
 Parameter passing is either:
• By value: pass the value of the variable
• By reference: pass a pointer (address) of the variable
containing the value
 Parameter passing is specified at the time the
function is defined
 Parameter passing is static and cannot change during
execution

HCT – ELE-3614 - Microcontrollers


HCT
2.0

Parameter Passing By Value


 Parameters a and b are passed by value:
int max(int a, int b) {
if(a > b) return(a);
else return(b);
}
...
k = max (v, 5) // v is any int variable
k = max (3, v);
...

HCT – ELE-3614 - Microcontrollers


HCT
2.0

Parameter Passing By Reference


 Arrays need to be passed by reference:

void activate(char *name, int *ID) {


...
}
...
// Call:
for(i=0;i<class.size;i++){
activate(class.name, &(class.ID));
}

HCT – ELE-3614 - Microcontrollers


HCT
2.0

Function Pointers
 Advanced feature used to reference (call) functions not by
their name but by their pointer:
• Used when selecting which function to execute using some indexing. A
function pointer table is created and properly initialized
• When passing the function reference as a parameter to another function
 Declaration of the variable function pointer:
typename (*fnptr)();
 Usage
Val = (*fnptr) (<parameters passed>);

HCT – ELE-3614 - Microcontrollers


HCT
2.0

Libraries
 C is built on standard libraries or user-defined libraries
 Standard libraries are:
• Stdio: to access the standard input/output (keyboard and display)
• Stdlib: to allocate memory and some other standard function
• Math: extended mathematical functions
• String: string manipulation library
• Time: System time manipulation functions
 Libraries are NOT automatically included in the program. User
needs to include them explicitly
 Include statement used for that purpose:
#include <stdio.h>
#include “user_header.h”

HCT – ELE-3614 - Microcontrollers

You might also like