0% found this document useful (0 votes)
26 views42 pages

C and C++

hiiiiiiiiiiiiiii
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
26 views42 pages

C and C++

hiiiiiiiiiiiiiii
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 42

C & C++

Introduction
• The C programming language was designed by Dennis Ritchie at Bell
Laboratories in the early 1970s
• Influenced by
– ALGOL 60 (1960),
– CPL (Cambridge, 1963),
– BCPL (Martin Richard, 1967),
– B (Ken Thompson, 1970)
• Traditionally used for systems programming, though this may be
changing in favor of C++
• Traditional C:
– The C Programming Language, by Brian Kernighan and Dennis Ritchie, 2nd
Edition, Prentice Hall
– Referred to as K&R
C Language

– C Language is the common language used in microcontrollers,


embedded systems and other hardware applications.
• Very portable: compilers exist for virtually every processor
• Easy-to-understand compilation
• Produces efficient code
• Fairly concise
Coding standards

• Common aims
– Reliability
– Portability
– Maintainability
– Testability
– Reusability
– Extensibility
– Readability
Some sample rules
• No function shall have more than 200 lines (30 would be even better)
– that is, 200 non-comment source lines
• Each new statement starts on a new line
– E.g., int a = 7; x = a+7; f(x,9); // violation!
• No macros shall be used except for source control
– using #ifdef and #ifndef
• Identifiers should be given descriptive names
– May contain common abbreviations and acronyms
– When used conventionally, x, y, i, j, etc., are descriptive
– Use the number_of_elements style rather than the numberOfElements style
– Type names and constants start with a capital letter
• E.g., Device_driver and Buffer_pool
– Identifiers shall not differ only by case
• E.g., Head and head // violation!
Some more sample rules
• Identifiers in an inner scope should not be identical to identifiers in an
outer scope
– E.g., int var = 9; { int var = 7; ++var; } // violation: var hides var
• Declarations shall be declared in the smallest possible scope
• Variables shall be initialized
– E.g., int var; // violation: var is not initialized
• Casts should be used only when essential
• Code should not depend on precedence rules below the level of
arithmetic expressions
E.g., x = a*b+c; // ok
if( a<b || c<=d) // violation: parenthesize (a<b) and (c<=d)
• Increment and decrement operations shall not be used as
subexpressions
– E.g., int x = v[++i]; // violation (that increment might be overlooked)
Standard C
• Standardized in 1989 by ANSI (American National Standards
Institute) known as ANSI C
• International standard (ISO) in 1990 which was adopted by
ANSI and is known as C89
• As part of the normal evolution process the standard was
updated in 1995 (C95) and 1999 (C99)
• C++ and C
– C++ extends C to include support for Object Oriented Programming
and other features that facilitate large software development
projects
– C is not strictly a subset of C++, but it is possible to write “Clean C”
that conforms to both the C++ and C standards.
Writing C Programs
• A programmer uses a text editor to create or modify
files containing C code.
• Code is also known as source code.
• A file containing source code is called a source file.
• After a C source file has been created, the programmer
must invoke the C compiler before the program can be
executed (run).
Header files
• The files that are specified in the include section is called as
header file
• These are precompiled files that has some functions
defined in them
• We can call those functions in our program by supplying
parameters
• Header file is given an extension .h
• C Source file is given an extension .c
Main function
• This is the entry point of a program
• When a file is executed, the start point is the main function
• From main function the flow goes as per the programmers
choice.
• There may or may not be other functions written by user in
a program
• Main function is compulsory for any c program
Writing the first program in C
#include<stdio.h>
int main()
{
printf(“Hello”);
return 0;
}

• This program prints Hello on the screen when we execute it


Data types in C
Name Description Size* Range*
char Character or small integer 1 byte signed: -128 to 127
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 2147483647


(long) unsigned: 0 to 4294967295

float Floating point number 4 bytes 3.4e +/- 38 (7 digits)

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

long double Long double precision 8 bytes 1.7e +/- 308 (15 digits)
floating point number
Variable types
• Local variable
Local variables are declared within the body of a function, and can only
be used within that function.

• Static variable
Another class of local variable is the static type. It is specified by the
keyword static in the variable declaration.
The most striking difference from a non-static local variable is, a static
variable is not destroyed on exit from the function.

• Global variable
A global variable declaration looks normal, but is located outside any of
the program's functions. So it is accessible to all functions.
• An example

int vc= 10; //global variable

int func (int x)


{
static int stat_var; //static local variable
int temp; //(normal) local variable
int name[50]; //(normal) local variable
……
}
Variable Definition vs Declaration

Definition Tell the compiler about the variable: its type and
name, as well as allocated a memory cell for the
variable

Declaration Describe information ``about'' the variable,


doesn’t allocate memory cell for the variable
Input and Output

• Input
– scanf(“%d”,&a);
– Gets an integer value from the user and stores it under the name
“a”
• Output
– printf(“%d”,a);
– Prints the value present in variable a on the screen
• Why “\n”
It introduces a new line on the terminal screen.
escape sequence
\a alert (bell) character \\ backslash
\b backspace \? question mark
\f formfeed \’ single quote
\n newline \” double quote
\r carriage return \000 octal number
\t horizontal tab \xhh hexadecimal number

\v vertical tab
Arithmetic Operations
Arithmetic Assignment Operators
Increment and Decrement Operators

awkward easy easiest

x = x+1; x += 1 x++

x = x-1; x -= 1 x--
Logical Operations
• What is “true” and “false” in C
In C, there is no specific data type to represent “true” and “false”. C uses value
“0” to represent “false”, and uses non-zero value to stand for “true”.
Logical Operators
A && B => A and B
A || B=> A or B
A == B => Is A equal to B?
A != B => Is A not equal to B?
A > B => Is A greater than B?
A >= B => Is A greater than or equal to B?
A < B => Is A less than B?
A <= B => Is A less than or equal to B?
• Don’t be confused
&& and || have different meanings from & and |.
& and | are bitwise operators.
Conditionals

• if statement
• If else
• Switch Case
Arrays & Strings
• Arrays
int ids[50];
char name[100];
int table_of_num[30][40];
• Accessing an array
ids[0] = 40;
i = ids[1] + j;
table_of_num[3][4] = 100;
Note: In C Array subscripts start at 0 and end one less than
the array size. [0 .. n-1]
Strings
• Strings are defined as arrays of characters.
• The only difference from a character array is, a symbol “\0”
is used to indicate the end of a string.
• For example, suppose we have a character array, char
name[8], and we store into it a string “Dave”.
Note: the length of this string 4, but it occupies 5 bytes.

D a v e \0
Functions
• Functions are easy to use; they allow complicated programs to be
broken into small blocks, each of which is easier to write, read,
and maintain. This is called modulation.

• How does a function look like?


returntype function_name(parameters…)
{
local variables declaration;
function code;
return result;
}
Pointers
• Pointer is the most beautiful (ugliest) part of C, but also
brings most trouble to C programmers. Over 90% bugs in
the C programs come from pointers.
“The International Obfuscated C Code Contest ”
(http://www.ioccc.org/)

• What is a pointer?
A pointer is a variable which contains the address in
memory of another variable.

In C we have a specific type for pointers.


Pointers
• Declaring a pointer variable
int * pointer;
char * name;
• How to obtain the address of a variable?
int x = 0x2233;
pointer = &x;
where & is called address of operator.

• How to get the value of the variable indicated by the pointer?


int y = *pointer;
• What happens in the memory?
• Suppose the address of variable x is 0x5200 in the above
example, so the value of the variable pointer is 0x5200.
X pointer
0x5200

33 22 00 00

0x5200 0x5203
C - Flow Control Statements
• Flow Control – Making the program behave in a particular manner
depending on the input given to the program
• Why do we need flow control?
– Not all program parts are executed all of the time( i.e. we want the program to
intelligently choose what to do).
• There are following types of flow control statements:
– If
– If-else
– For
– While
– Do-while
– Nesting loops
– Switch
Introduction to C++ Programming
• C++ language
– Facilitates structured and disciplined approach to computer
program design
• Following several examples
– Illustrate many important features of C++
– Each analyzed one statement at a time
• Structured programming
History of C++
• History of C++
– Extension of C
– Early 1980s: Bjarne Stroustrup (Bell Laboratories)
– “Spruces up” C
– Provides capabilities for object-oriented programming
• Objects: reusable software components
– Model items in real world
• Object-oriented programs
– Easy to understand, correct and modify
– Hybrid language
• C-like style
• Object-oriented style
• Both
C++ Standard Library

• C++ programs
– Built from pieces called classes and functions
• C++ standard library
– Rich collections of existing classes and functions
• “Building block approach” to creating programs
– “Software reuse”
C++ for Embedded Systems

• Of higher level languages, C++ is the closest to assembly


languages
– bit manipulation instructions
– pointers (indirect addressing)
• Most microcontrollers have available C++ compilers
• Believe it or not, it is just ordinary C++ with little additions !
Basics of a Typical C++ Environment
Program is created in
Editor Disk the editor and stored
on disk.

• Phases of C++ Programs: Preprocessor Disk Preprocessor program


processes the code.
Compiler creates
1. Edit Compiler Disk object code and stores
it on disk.
2. Preprocess Linker
Linker links the object
Disk code with the libraries,
3. Compile Primary
creates a.out and
stores it on disk
Memory
4. Link Loader

Loader puts program


5. Load Disk ..
in memory.
..

6. Execute ..

Primary
Memory
CPU CPU takes each
instruction and
executes it, possibly
.. storing new data
..
..
values as the program
executes.
• Input/output
– cin
• Standard input stream
• Normally keyboard
– cout
• Standard output stream
• Normally computer screen
– cerr
• Standard error stream
• Display error messages
Hardware Trends
• Capacities of computers
– Approximately double every year or two
– Memory used to execute programs
– Amount of secondary storage
• Disk storage
• Hold programs and data over long term
– Processor speeds
• Speed at which computers execute programs
Write a program in C++
• Example:
#include <iostream> using namespace std; //namespace
int main ()
{
cout << "Hello world!";
return 0;
}
Advantages of High Level Language

• User-friendly
• Similar to English with vocabulary of words and
symbols
• Therefore it is easier to learn.
• They require less time to write.
• They are easier to maintain.
• Portable
Disadvantages of High Level Language
• A high-level language has to be translated into the machine
language by a translator and thus a price in computer time
is paid.

• The object code generated by a translator might be


inefficient Compared to an equivalent assembly language
program.
Applications of C and C++
List of Application:
• Operating Systems
– Network Drivers
– Print Spoolers
• Language Compilers
– Assemblers
– Text Editors
• Modern Programs
– Data Bases
– Language Interpreters
• Simulators
– Utilities
– Embedded System

You might also like