LO2 - Introduction To C Language
LO2 - Introduction To C Language
LO2 - Introduction To C Language
2.0
Introduction to
C Language
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
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)
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, …) {
…
}
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”
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) {
…
}
}
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
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)
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 ‘_’
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;
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
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
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
Increment/Decrement
Use of Operators
int a,b,c,i,j,k;
float m,n,p,q;
// Addition
a = b + 3;
b -= 5;
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
Control Sequences
If statement
While statement
For statement
Switch statement
If statement
if (k == 0) {
printf(“Main Operation\n”);
b = 1;
}
else {
k = 7;
b = 2;
}
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.
For Loop
for (k = 0; k < 200; k++) {
if(a[k] == 12) break;
else continue;
}
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;
User-Defined Types
Users can define types that will have a global scope
and can be used to dynamically allocate memory:
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
Functions
C structure uses functions as the sole container.
<return_type> <function_name> (<param_list>) {
<local variables definition>
<function body>
}
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));
}
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
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>);
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”