introduction of c langauge(i unit)

129
MAHARSHI ARVIND INSTITUTE OF ENGINEERING TECHNOLOGY, JAIPUR B.TECH II SEM FUNDAMENTAL OF COMPUTER PROGRAMMING Presented by Er. PRASHANT KUMAR SHARMA( CSE DEPT)

Upload: prashant-sharma

Post on 14-Apr-2017

150 views

Category:

Engineering


1 download

TRANSCRIPT

Page 1: introduction of c langauge(I unit)

MAHARSHI ARVIND INSTITUTE OF ENGINEERING TECHNOLOGY, JAIPUR

B.TECH II SEM

FUNDAMENTAL OF COMPUTER PROGRAMMING

Presented by

Er. PRASHANT KUMAR SHARMA( CSE DEPT)

Page 2: introduction of c langauge(I unit)

Unit-1

INTRODUCTION

Page 3: introduction of c langauge(I unit)

3

A Brief History of C language In the early 1970s, Dennis Ritchie of Bell Laboratories

was engaged in a project to develop new operating system. C programming language was then developed.

In the early 1980's, also at Bell Laboratories, another C++ language was created. This new language was developed by Bjarne Stroustrup and was called C++ which was designed with OOP (Object Oriented Programming) features added to C without significantly changing the C component.

Page 4: introduction of c langauge(I unit)

C Preprocessor Overview Preprocessor Directives Conditional Compilation Predefined Symbolic Constants

Page 5: introduction of c langauge(I unit)

Overview Six phases to execute C:

1. Edit2. Preprocess3. Compile4. Link5. Load6. Execute

Page 6: introduction of c langauge(I unit)

C Preprocessor All preprocessor directives begin with # Possible actions

Inclusion of other filesDefinition of symbolic constants & macrosConditional compilation of program codeConditional compilation of preprocessor

directives

Page 7: introduction of c langauge(I unit)

Preprocessor Directives

#include preprocessor directive #include <filename>

For standard library header files Location based on system

#include "filename" For programmer-defined header files

Function, structure, typedef definitions & global variables

Located in the same folder as the file being compiled

Page 8: introduction of c langauge(I unit)

Preprocessor Directives

#define for symbolic constants#define identifier text

Creates symbolic constants The “identifier” is replaced by “text” in the

programExample

#define PI 3.14area = PI * radius * radius; Replaced by “area = 3.14 * radius * radius” by

preprocessor before compilation

Page 9: introduction of c langauge(I unit)

Preprocessor Directives

#define for macros#define macro-identifier text

Can have arguments The macro is “expanded” in the program

Example#define AREA(x) ( (PI) * (x) * (x))circle_area = AREA(5); Expanded to “circle_area = ((3.14)*(5)*(5))” by

preprocessor before compilation

Page 10: introduction of c langauge(I unit)

Conditional Compilation

Controls the execution of preprocessor directives & compilation of codeDefine NULL, if it hasn’t been defined yet#if !defined(NULL)

#define NULL 0#endif

Use to comment out code (for comments)#if 0

code prevented from compiling#endif

Page 11: introduction of c langauge(I unit)

Predefined Symbolic Constants

#include <stdio.h> int main(){

printf("%d\n%s\n%s\n%s\n", __LINE__, __FILE__, __DATE__, __TIME__);

}

Output: 3example.cOct 13 200319:27:57

line #, file name, compiled date, compiled timeSee example.c

Page 12: introduction of c langauge(I unit)

Concept of Pre-ProcessorOutline17.1 Introduction17.2 The #include Preprocessor Directive17.3 The #define Preprocessor Directive: Symbolic Constants

17.4 The #define Preprocessor Directive: Macros17.5 Conditional Compilation17.6 The #error and #pragma Preprocessor Directives17.7 The # and ## Operators17.8 Line Numbers17.9 Predefined Symbolic Constants17.10 Assertions

Page 13: introduction of c langauge(I unit)

Introduction preprocessing

occurs before a program is compiled. inclusion of other files definition of symbolic constants and macros, conditional compilation of program code conditional execution of preprocessor directives

Format of preprocessor directives: lines begin with # only whitespace characters before directives on a

line they are not C++ statements - no semicolon (;)

Page 14: introduction of c langauge(I unit)

The #include Preprocessor Directive #include

copy of a specified file included in place of the directive #include <filename> - searches standard library for file (use for standard library files)#include "filename" - searches current directory, then

standard library (use for user-defined files)

Used for loading header files (#include <iostream>) programs with multiple source files to be compiled together header file - has common declarations and definitions

(classes, structures, function prototypes) #include statement in each file

Page 15: introduction of c langauge(I unit)

The #define Preprocessor Directive: Symbolic Constants

#define preprocessor directive used to create symbolic constants and

macros. Symbolic constants

when program compiled, all occurrences of symbolic constant replaced with replacement text

Format: #define identifier replacement-text Example: #define PI 3.14159 everything to right of identifier replaces text#define PI = 3.14159

replaces "PI" with " = 3.14159", probably results in an error cannot redefine symbolic constants with more #define

statements

Page 16: introduction of c langauge(I unit)

The #define Preprocessor Directive: Macros Macro - operation defined in #define

intended for C programs macro without arguments: treated like a symbolic constant macro with arguments: arguments substituted for

replacement text, macro expanded performs a text substitution - no data type checking

Example: #define CIRCLE_AREA( x ) ( PI * ( x ) * ( x ) )

area = CIRCLE_AREA( 4 ); becomes

area = ( 3.14159 * ( 4 ) * ( 4 ) );

Page 17: introduction of c langauge(I unit)

The #define Preprocessor Directive: Macros (II) use parenthesis:

without them, #define CIRCLE_AREA( x ) PI * ( x ) * ( x ) area = CIRCLE_AREA( c + 2 );

becomesarea = 3.14159 * c + 2 * c + 2;

which evaluates incorrectly

multiple arguments:#define RECTANGLE_AREA( x, y ) ( ( x ) * ( y ) ) rectArea = RECTANGLE_AREA( a + 4, b + 7 );

becomesrectArea = ( ( a + 4 ) * ( b + 7 ) );

#undef undefines a symbolic constant or macro, which can later be

redefined

Page 18: introduction of c langauge(I unit)

The #error and #pragma Preprocessor Directives #error tokens

tokens - sequences of characters separated by spaces "I like C++" has 3 tokens

prints message and tokens (depends on implementation) for example: when #error encountered, tokens displayed

and preprocessing stops (program does not compile)

#pragma tokens implementation defined action (consult compiler

documentation) pragmas not recognized by compiler are ignored

Page 19: introduction of c langauge(I unit)

The # and ## Operators # - replacement text token converted to string with

quotes #define HELLO( x ) cout << "Hello, " #x << endl;

HELLO(John) becomescout << "Hello, " "John" << endl;

strings separated by whitespace are concatenated when using cout

## - concatenates two tokens#define TOKENCONCAT( x, y ) x ## y

TOKENCONCAT( O, K ) becomesOK 

Notice #

Page 20: introduction of c langauge(I unit)

Predefined Symbolic Constants Five predefined symbolic constants

cannot be used in #define or #undef

Symbolic constant Description __LINE__ The line number of the current source code line (an integer

constant). __FILE__ The presumed name of the source file (a string). __DATE__ The date the source file is compiled (a string of the form

"Mmm dd yyyy" such as "Jan 19 2001"). __TIME__ The time the source file is compiled (a string literal of the

form "hh:mm:ss").

Page 21: introduction of c langauge(I unit)

Lifecycle of a C/C++ Program

C++ source code

Makefile

Programmer(you)

object code (binary, one per compilation unit) .o

make“make” utility

xterm

console/terminal/window

Runtime/utility libraries

(binary) .lib .a .dll .so

gcc, etc.compiler

linklinker

E-mail

executableprogram

Eclipse

debugger

precompiler

compiler

link

turnin/checkin

An “IDE”WebCAT

Visual Studio

window

compile

Page 22: introduction of c langauge(I unit)

Three Stages of CompilationStage 1: Preprocessing

Performed by a program called the preprocessor Modifies the source code (in RAM) according to

preprocessor directives (preprocessor commands) embedded in the source code

Strips comments and whitespace from the codeThe source code as stored on disk is not modified.

Page 23: introduction of c langauge(I unit)

Stages of Compilation (con’t)Stage 2: Compilation

Performed by a program called the compilerTranslates the preprocessor-modified source

code into object code (machine code)Checks for syntax errors and warningsSaves the object code to a disk file, if instructed

to do so (we will not do this).o If any compiler errors are received, no object code

file will be generated.o An object code file will be generated if only

warnings, not errors, are received.

Page 24: introduction of c langauge(I unit)

Stages of Compilation (con’t)Stage 3: Linking

Combines the program object code with other object code to produce the executable file.

The other object code can come from the Run-Time Library, other libraries, or object files that you have created.

Saves the executable code to a disk file. On the Linux system, that file is called a.out.

o If any linker errors are received, no executable file will be generated.

Page 25: introduction of c langauge(I unit)

Program Development Using gcc

Source File pgm.c

Program Object Code File pgm.o

Executable File a.out

Preprocessor

Modified Source Code in RAM

Compiler

Linker

Other Object Code Files (if any)

Editor

Page 26: introduction of c langauge(I unit)

A Simple C Program /* Filename: hello.c Author: Brian Kernighan & Dennis Ritchie Date written: ?/?/1978 Description: This program prints the greeting

“Hello, World!” */ #include <stdio.h> int main ( ) { printf (“Hello, World!\n”) ; return 0 ; }

Page 27: introduction of c langauge(I unit)

Anatomy of a C Program program header comment

preprocessor directives (if any)

int main ( ) { statement(s) return 0 ; }

Page 28: introduction of c langauge(I unit)

Program Header Comment A comment is descriptive text used to help a

reader of the program understand its content.

All comments must begin with the characters /* and end with the characters */

These are called comment delimiters The program header comment always

comes first. Look at the class web page for the required

contents of our header comment.

Page 29: introduction of c langauge(I unit)

Preprocessor Directives Lines that begin with a # in column 1 are

called preprocessor directives (commands).

Example: the #include <stdio.h> directive causes the preprocessor to include a copy of the standard input/output header file stdio.h at this point in the code.

This header file was included because it contains information about the printf ( ) function that is used in this program.

Page 30: introduction of c langauge(I unit)

int main ( )

Every program must have a function called main. This is where program execution begins.

main() is placed in the source code file as the first function for readability.

The reserved word “int” indicates that main() returns an integer value.

The parentheses following the reserved word “main” indicate that it is a function.

Page 31: introduction of c langauge(I unit)

The Function Body A left brace (curly bracket) -- { -- begins the

body of every function. A corresponding right brace -- } -- ends the function body.

The style is to place these braces on separate lines in column 1 and to indent the entire function body 3 to 5 spaces.

Page 32: introduction of c langauge(I unit)

printf (“Hello, World!\n”) ;

This line is a C statement. It is a call to the function printf ( ) with a

single argument (parameter), namely the string “Hello, World!\n”.

Even though a string may contain many characters, the string itself should be thought of as a single quantity.

Notice that this line ends with a semicolon. All statements in C end with a semicolon.

Page 33: introduction of c langauge(I unit)

33

A Simple C Program/* Take a number multiply it by 10 and display it */

#include <stdio.h>

main(){

int number, result; printf("Type in a number \n");scanf("%d", &number);result = number *10;printf("The number multiplied by 10 equals %d\n", result);

}

Sample Program OutputType in a number23The number multiplied by 10 equals 230

Page 34: introduction of c langauge(I unit)

34

A Simple C Program/* Take a number multiply it by 10 and display it */

#include <stdio.h>

main(){

int number, result; printf("Type in a number \n");scanf("%d", &number);result = number *10;printf("The number multiplied by 10 equals %d\n", result);

}

Sample Program OutputType in a number23The number multiplied by 10 equals 230

Comments are set between /* and */

Page 35: introduction of c langauge(I unit)

35

A Simple C Program/* Take a number multiply it by 10 and display it */

#include <stdio.h>

main(){

int number, result; printf("Type in a number \n");scanf("%d", &number);result = number *10;printf("The number multiplied by 10 equals %d\n", result);

}

Sample Program OutputType in a number23The number multiplied by 10 equals 230

The C pre-processor replaces this directivewith the contents of the stdio.h header file from the standard C library.

Page 36: introduction of c langauge(I unit)

36

A Simple C Program/* Take a number multiply it by 10 and display it */

#include <stdio.h>

main(){

int number, result; printf("Type in a number \n");scanf("%d", &number);result = number *10;printf("The number multiplied by 10 equals %d\n", result);

}

Sample Program OutputType in a number23The number multiplied by 10 equals 230

Every C program must have one main function.

Page 37: introduction of c langauge(I unit)

37

A Simple C Program/* Take a number multiply it by 10 and display it */

#include <stdio.h>

main(){

int number, result; printf("Type in a number \n");scanf("%d", &number);result = number *10;printf("The number multiplied by 10 equals %d\n", result);

}

Sample Program OutputType in a number23The number multiplied by 10 equals 230

Each variable must be explicitly defined as a specific type.

Page 38: introduction of c langauge(I unit)

38

A Simple C Program/* Take a number multiply it by 10 and display it */

#include <stdio.h>

main(){

int number, result; printf("Type in a number \n");scanf("%d", &number);result = number *10;printf("The number multiplied by 10 equals %d\n", result);

}

Sample Program OutputType in a number23The number multiplied by 10 equals 230

The stdio library defines the printf() function for creating output.

Page 39: introduction of c langauge(I unit)

39

A Simple C Program/* Take a number multiply it by 10 and display it */

#include <stdio.h>

main(){

int number, result; printf("Type in a number \n");scanf("%d", &number);result = number *10;printf("The number multiplied by 10 equals %d\n", result);

}

Sample Program OutputType in a number23The number multiplied by 10 equals 230

The stdio library defines the printf() function for creating output.

\n is the newline character

Page 40: introduction of c langauge(I unit)

40

A Simple C Program/* Take a number multiply it by 10 and display it */

#include <stdio.h>

main(){

int number, result; printf("Type in a number \n");scanf("%d", &number);result = number *10;printf("The number multiplied by 10 equals %d\n", result);

}

Sample Program OutputType in a number23The number multiplied by 10 equals 230

The stdio library defines the scanf() function for capturing input.

Page 41: introduction of c langauge(I unit)

41

A Simple C Program/* Take a number multiply it by 10 and display it */

#include <stdio.h>

main(){

int number, result; printf("Type in a number \n");scanf("%d", &number);result = number *10;printf("The number multiplied by 10 equals %d\n", result);

}

Sample Program OutputType in a number23The number multiplied by 10 equals 230

%d tells scanf() to interpret the input as a decimal value

Page 42: introduction of c langauge(I unit)

42

A Simple C Program/* Take a number multiply it by 10 and display it */

#include <stdio.h>

main(){

int number, result; printf("Type in a number \n");scanf("%d", &number);result = number *10;printf("The number multiplied by 10 equals %d\n", result);

}

Sample Program OutputType in a number23The number multiplied by 10 equals 230

The = operator is used for assignment.

The * operator is used for multiplication.

Page 43: introduction of c langauge(I unit)

43

A Simple C Program/* Take a number multiply it by 10 and display it */

#include <stdio.h>

main(){

int number, result; printf("Type in a number \n");scanf("%d", &number);result = number *10;printf("The number multiplied by 10 equals %d\n", result);

}

Sample Program OutputType in a number23The number multiplied by 10 equals 230

%d tells printf() to treat the value of the result variable as a decimal nbr.

Page 44: introduction of c langauge(I unit)

44

Simple C++ Program/* Take a number multiply it by 10 and display it */

#include <iostream>

int main(){

int number, result; std::cout<<"Type in a number “<< std::endl;std::cin>>number;result = number *10;std::cout<<"The number multiplied by 10 equals “<<result;

}

Sample Program OutputType in a number23The number multiplied by 10 equals 230

C++ pre-processor directives include different versions of the standard library packages.

Page 45: introduction of c langauge(I unit)

45

Simple C++ Program/* Take a number multiply it by 10 and display it */

#include <iostream>

int main(){

int number, result; std::cout <<"Type in a number “<< std::endl;std::cin >>number;result = number *10;std::cout<<"The number multiplied by 10 equals “<<result;

}

Sample Program OutputType in a number23The number multiplied by 10 equals 230

std is an object which you can send messages to—messages such as:

cout, cin, & endl.

Page 46: introduction of c langauge(I unit)

46

Simple C++ Program/* Take a number multiply it by 10 and display it */

#include <iostream>using namespace std;

int main(){

int number, result; cout <<"Type in a number “ << endl;cin>>number;result = number *10;cout<<"The number multiplied by 10 equals “ <<result;

}

Sample Program OutputType in a number23The number multiplied by 10 equals 230

You can use an object’s namespace, to keep from having to specify the name of the object each time you send it a message.

Page 47: introduction of c langauge(I unit)

47

How to run compiled files

The compiling commands create an executable file known as a.out unless specified otherwise.

To execute your program, type ./a.out and press Enter.

Page 48: introduction of c langauge(I unit)

48

Compilation Details

object.h

object.cpp

main.cpp

object.s

main.s

object.o

main.o

Output

Source code Assembly Machine Code

Page 49: introduction of c langauge(I unit)

Simple Data Types in C

Page 50: introduction of c langauge(I unit)

Objectives

Be able to explain to others what a data type is

Be able to use basic data types in C programs

Be able to see the inaccuracies and limitations introduced by machine representations of numbersCox 50

Page 51: introduction of c langauge(I unit)

Cox Simple Data Types 51

Everything is Just a Bunch of Bits Bits can represent many different things

Depends on interpretation

You and your program must keep track of what kind of data is at each location in the computer’s memoryE.g., program data types

Page 52: introduction of c langauge(I unit)

Cox Simple Data Types 52

Big Picture Processor works with finite-sized data All data implemented as a sequence of bits

Bit = 0 or 1 Represents the level of an electrical charge

Byte = 8 bits

Word = largest data size handled by processor 32 bits on most older computers 64 bits on most new computers

Page 53: introduction of c langauge(I unit)

Cox Simple Data Types 53

Data types in COnly really four basic types:

char int (short, long, long long, unsigned) float double

Size of these types on CLEAR machines:

Sizes of these typesvary from one machineto another!

Type Size (bytes)char 1int 4short 2long 8long long 8float 4double 8

Page 54: introduction of c langauge(I unit)

Cox Simple Data Types 54

Characters (char)

Roman alphabet, punctuation, digits, and other symbols:Can encode within one byte (256 symbols)ASCII encoding (man ascii for details)

In C:

char a_char = ’a’;char newline_char = ’\n’;char tab_char = ’\t’;char backslash_char = ’\\’;

Page 55: introduction of c langauge(I unit)

Cox Simple Data Types 55

ASCIIFrom “man ascii”:

| 0 NUL| 1 SOH| 2 STX| 3 ETX| 4 EOT| 5 ENQ| 6 ACK| 7 BEL|| 8 BS | 9 HT | 10 NL | 11 VT | 12 NP | 13 CR | 14 SO | 15 SI || 16 DLE| 17 DC1| 18 DC2| 19 DC3| 20 DC4| 21 NAK| 22 SYN| 23 ETB|| 24 CAN| 25 EM | 26 SUB| 27 ESC| 28 FS | 29 GS | 30 RS | 31 US || 32 SP | 33 ! | 34 " | 35 # | 36 $ | 37 % | 38 & | 39 ' || 40 ( | 41 ) | 42 * | 43 + | 44 , | 45 - | 46 . | 47 / || 48 0 | 49 1 | 50 2 | 51 3 | 52 4 | 53 5 | 54 6 | 55 7 || 56 8 | 57 9 | 58 : | 59 ; | 60 < | 61 = | 62 > | 63 ? || 64 @ | 65 A | 66 B | 67 C | 68 D | 69 E | 70 F | 71 G || 72 H | 73 I | 74 J | 75 K | 76 L | 77 M | 78 N | 79 O || 80 P | 81 Q | 82 R | 83 S | 84 T | 85 U | 86 V | 87 W || 88 X | 89 Y | 90 Z | 91 [ | 92 \ | 93 ] | 94 ^ | 95 _ || 96 ` | 97 a | 98 b | 99 c |100 d |101 e |102 f |103 g ||104 h |105 i |106 j |107 k |108 l |109 m |110 n |111 o ||112 p |113 q |114 r |115 s |116 t |117 u |118 v |119 w ||120 x |121 y |122 z |123 { |124 | |125 } |126 ~ |127 DEL|

Special control

characters

Page 56: introduction of c langauge(I unit)

Cox Simple Data Types 56

Characters are just numbers What does this function do?charfun(char c){ char new_c;

if ((c >= ’A’) && (c <= ’Z’)) new_c = c - ’A’ + ’a’; else new_c = c;

return (new_c);}

return type

procedure name

argument typeand name

local variabletype and name

Math oncharacters!

comparisonswith characters!

Page 57: introduction of c langauge(I unit)

Cox Simple Data Types 57

Integers Fundamental problem:

Fixed-size representation can’t encode all numbers

Standard low-level solution:Limit number range and precision

Usually sufficient Potential source of bugs

Signed and unsigned variantsunsigned modifier can be used with any sized

integer (short, long, or long long)

Page 58: introduction of c langauge(I unit)

Cox Simple Data Types 58

Integer RepresentationsBase 2 Base 16 Unsigned 2’s Comp.

0000 0 0 0 0001 1 1 1 0010 2 2 2 0011 3 3 3 0100 4 4 4 0101 5 5 5 0110 6 6 6 0111 7 7 7 1000 8 8 -8 1001 9 9 -7 1010 A 10 -6 1011 B 11 -5 1100 C 12 -4 1101 D 13 -3 1110 E 14 -2 1111 F 15 -1

0000 0001

0010

0011

0100

0101

0110

011110001001

1011

1100

1101

1010

1110

11110

1

2

3

4

5

6

789

A

D

C

B

E

F0 1

2

3

4

5

6789

10

11

12

13

1415

0 1

-8

34

56

7

2

-7-6

-5-4-3

-2-1

Why one more negative than positive?

Page 59: introduction of c langauge(I unit)

Cox Simple Data Types 59

Integer RepresentationsMath for n bits:

Define

1

0

2)(2n

ii

i xxUB

2

01

1 22)(2n

ii

in

n xxxTB

01 xxx n

sign bit0=non-negative

1=negative

Base 2 Base 16 Unsigned 2’s Comp. 0000 0 0 0 0001 1 1 1 0010 2 2 2 0011 3 3 3 0100 4 4 4 0101 5 5 5 0110 6 6 6 0111 7 7 7 1000 8 8 -8 1001 9 9 -7 1010 A 10 -6 1011 B 11 -5 1100 C 12 -4 1101 D 13 -3 1110 E 14 -2 1111 F 15 -1

Page 60: introduction of c langauge(I unit)

Cox Simple Data Types 60

Integer Ranges Unsigned

UMinn … UMaxn = 0 … 2n-1: 32 bits: 0 ... 4,294,967,295 unsigned int 64 bits: 0 ... 18,446,744,073,709,551,615 unsigned long int

2’s Complement TMinn … TMaxn = -2n-1 … 2n-1-1:

32 bits: -2,147,483,648 ... 2,147,483,647 int 64 bits: -9,223,372,036,854,775,808 … 9,223,372,036,854,775,807 long int

Note: C numeric ranges are platform dependent! #include <limits.h> to define ULONG_MAX, UINT_MIN, INT_MAX, …

Page 61: introduction of c langauge(I unit)

Cox Simple Data Types 61

Detecting Overflow in Programs Some high-level languages (ML, Ada, …):

Overflow causes exception that can be handled

C: Overflow causes no special event Programmer must check, if desired

E.g., given a, b, and c=UAddn(a,b) – overflow?

Claim: Overflow iff c < a (Or similarly, iff c < b)

Proof: Know 0 b < 2n

If no overflow, c = (a + b) mod 2n = a + b a + 0 = aIf overflow, c = (a + b) mod 2n = a + b – 2n < a

Page 62: introduction of c langauge(I unit)

Cox Simple Data Types 62

Bit Shifting as Multiplication

0 0 1 1 = 3

0 1 1 0 = 6

1 1 0 1 = -3

1 0 1 0 = -6

Shift left (x << 1) multiplies by 2:

Works for unsigned, 2’s complementCan overflow

In decimal, same idea multiplies by 10: e.g., 42 420

Page 63: introduction of c langauge(I unit)

Cox Simple Data Types 63

Bit Shifting as Division

0 1 1 1 = 7

0 0 1 1 = 3

1 0 0 1 = -7

1 1 0 0 = -4Always rounds down!

Arithmetic shift right (x >> 1) divides by 2 for 2’s complement:

0 1 1 1 = 7

0 0 1 1 = 3

1 0 0 1 = 9

0 1 0 0 = 4Always rounds down!

Logical shift right (x >> 1) divides by 2 for unsigned:

Page 64: introduction of c langauge(I unit)

Cox Simple Data Types 64

A Sampling of Integer PropertiesMostly as usual, e.g.:

0 is identity for +, -1 is identity for ×, ÷+, -, × are associative+, × are commutative× distributes over +, -

Some surprises, e.g.:÷ doesn’t distribute over +, - (a,b > 0 a + b > a)

Why should you care?– Programmer should be aware of behavior of their programs– Compiler uses such properties in optimizations

For both unsigned & 2’s complement:

Page 65: introduction of c langauge(I unit)

Cox Simple Data Types 65

Beware of Sign Conversions in C Beware implicit or explicit conversions between unsigned and

signed representations!

One of many common mistakes:

Always false(!) because -1 is converted to unsigned, yielding UMaxn

unsigned int u;…if (u > -1) …

? What’s wrong? ?

Page 66: introduction of c langauge(I unit)

Cox Simple Data Types 66

Non-Integral Numbers: How?

Fixed-size representationsRational numbers (i.e., pairs of integers)Fixed-point (use integer, remember where

point is)Floating-point (scientific notation)

Variable-size representationsSums of fractions (e.g., Taylor-series)Unbounded-length series of digits/bits

Page 67: introduction of c langauge(I unit)

Cox Simple Data Types 67

Floating-point

Binary version of scientific notation

1.001101110 × 25 = 100110.1110= 32 + 4 + 2 + 1/2 + 1/4

+ 1/8 = 38.875

-1.011 × 2-3 = -.001011= - (1/8 + 1/32 + 1/64)= -.171875

binary point

Page 68: introduction of c langauge(I unit)

Cox Simple Data Types 68

FP Overflow & Underflow Fixed-sized representation leads to

limitations

Expressiblenegative values

Expressiblepositive values

Negativeunderflow

Positiveunderflow

Positiveoverflow

Negativeoverflow

Zero

Large positive exponent.Unlike integer arithmetic, overflow imprecise result (), not inaccurate

resultRound to +

Round to -

Large negative exponentRound to zero

Page 69: introduction of c langauge(I unit)

Cox Simple Data Types 69

FP Representation

Fixed-size representationUsing more significand bits increased

precisionUsing more exponent bits increased

range Typically, fixed # of bits for each part, for

simplicity

1.001101110 × 25

significand exponent

Page 70: introduction of c langauge(I unit)

Cox Simple Data Types 70

FP vs. Integer Results

int i = 20 / 3;float f = 20.0 / 3.0;

True mathematical answer: 20 3 = 6 2/3

i = ?

f = ?

6

6.666667

Integer division ignores remainder

FP arithmetic rounds result

Page 71: introduction of c langauge(I unit)

Cox Simple Data Types 71

FP Integer Conversions in Cint i = 3.3 * 5;float f = i;

True mathematical answer: 3.3 5 = 16 ½

i = ?

f = ?

16

16.0

Converts 5 5.0 – Truncates result 16 ½ 16

integer FP:Can lose precision

Rounds, if necessary

32-bit int fits in double-precision

FP

FP integer:Truncate fractionIf out of range, undefined – not

error

Page 72: introduction of c langauge(I unit)

Cox Simple Data Types 72

What about other types? Booleans

A late addition to C

StringsWe’ll cover these in a later class

Enumerated typesA restricted set of integers

Complex NumbersNot covered

Page 73: introduction of c langauge(I unit)

Cox Simple Data Types 73

Booleans

One bit representation0 is false1 is true

One byte or word representation Inconvenient to manipulate only one bitTwo common encodings:

Wastes space, but space is usually cheap

0000…0000 is false0000…0001 is trueall other words are garbage

0000…0000 is falseall other words are true

Page 74: introduction of c langauge(I unit)

Cox Simple Data Types 74

Booleans in C

bool added to C in 1999

Many programmers had already defined their own Boolean typeTo avoid conflict bool is disabled by default

#include <stdbool.h>

bool bool1 = true;bool bool2 = false;

Important!Compiler needs this or itwon't know about "bool"!

Page 75: introduction of c langauge(I unit)

Cox Simple Data Types 75

C’s Common Boolean Operations C extends definitions to integers

Booleans are encoded as integers 0 == false non-0 == true

Logical AND: 0 && 4 == 0 3 && 4 == 1 3 && 0 == 0 Logical OR: 0 || 4 == 1 3 || 4 == 1 3 || 0 == 1 Logical NOT: ! 4 == 0 ! 0 == 1

&& and || short-circuit Evaluate 2nd argument only if necessary E.g., 0 && error-producing-code == 0

Page 76: introduction of c langauge(I unit)

Cox Simple Data Types 76

Enumerated Types E.g., a Color = red, blue, black, or yellow

Small (finite) number of choicesBooleans & characters are common special

casesPick arbitrary bit patterns for each

Not enforced in CActually just integersCan assign values outside of the enumerationCould cause bugs

Page 77: introduction of c langauge(I unit)

Cox Simple Data Types 77

Enumerated Types in Cenum Color {RED, WHITE, BLACK, YELLOW};enum Color my_color = RED;

Pre-C99 Boolean definition:

enum Bool {false=0, true=1};typedef enum Bool bool;bool my_bool = true;

Alternative style:enum AColor {COLOR_RED, COLOR_WHITE, COLOR_BLACK, COLOR_YELLOW};typedef enum AColor color_t;color_t my_color = COLOR_RED;

The new type name is“enum Color”

Page 78: introduction of c langauge(I unit)

Enumeration Type (continued)

The syntax for enumeration type is:

value1, value2, … are identifiers called enumerators

value1 < value2 < value3 <...

Page 79: introduction of c langauge(I unit)

Enumeration Type (continued)

Enumeration type is an ordered set of values

If a value has been used in one enumeration type It cannot be used by another in the same

block

The same rules apply to enumeration types declared outside of any blocks

Page 80: introduction of c langauge(I unit)
Page 81: introduction of c langauge(I unit)
Page 82: introduction of c langauge(I unit)
Page 83: introduction of c langauge(I unit)

Scope Rules and Storage Types

Page 84: introduction of c langauge(I unit)

CS-2303, C-Term 2010 84

Data Storage in Memory

Variables may be automatic or static

Automatic variables may only be declared within functions and compound statements (blocks)

Storage allocated when function or block is entered Storage is released when function returns or block exits

Parameters and result are (somewhat) like automatic variables

Storage is allocated and initialized by caller of function Storage is released after function returns to caller.

Page 85: introduction of c langauge(I unit)

CS-2303, C-Term 2010 85

Scope

Identifiers declared within a function or compound statement are visible only from the point of declaration to the end of that function or compound statement.

Like Java

Page 86: introduction of c langauge(I unit)

CS-2303, C-Term 2010 86

Example

int fcn (float a, int b) {int i;double g;

for (i = 0; i < b; i++) { double h = i*g;

loop body – may access a, b, i, g, h} // for(i…)

fcn body – may access a, b, i, g} // int fcn( … )

i is visible from this point to end of fcng is visible from this point

to end of fcn

h is only visible from this point to end of loop!

Page 87: introduction of c langauge(I unit)

CS-2303, C-Term 2010 87

Static variables may be declared within or outside of functions

Storage allocated when program is initialized Storage is released when program exits

Static variables outside of functions may be visible to linker

Compiler sets aside storage for all static variables at compiler or link time

Values retained across function calls

Initialization must evaluate to compile-time constant

Static Data – Very different

Page 88: introduction of c langauge(I unit)

CS-2303, C-Term 2010 88

Static Variable Examplesint j; //static, visible to linker & all functsstatic float f; // not visible to linker, visible to

// to all functions in this program

int fcn (float a, int b) {// nothing inside of {} is visible to linkerint i = b; //automaticdouble g; //automaticstatic double h; //static, not visible to

// linker; value retained from call to call

body – may access j, f, a, b, i, g, h

} // int fcn( … )

Page 89: introduction of c langauge(I unit)

CS-2303, C-Term 2010 89

Static Variable Examples (continued)

int j; //static, visible to linker & all functsstatic float f; // not visible to linker, visible to

// to all functions in this program

int fcn (float a, int b) {// nothing inside of {} is visible to linkerint i = b; //automaticdouble g; //automaticstatic double h; //static, not visible to

// linker; value retained from call to call

body – may access j, f, a, b, i, g, h

} // int fcn( … )

Declaration outside any

function:– always static

static storage class:– not

visible to linker

Page 90: introduction of c langauge(I unit)

CS-2303, C-Term 2010 90

Static Variable Examples (continued)

int j; //static, visible to linker & all functsstatic float f; // not visible to linker, visible to

// to all functions in this program

int fcn (float a, int b) {// nothing inside of {} is visible to linkerint i = b; //automaticdouble g; //automaticstatic double h; //static, not visible to

// linker; value retained from call to call

body – may access j, f, a, b, i, g, h

} // int fcn( … )

Inside f

unction:– defa

ult is

automatic

static

storag

e clas

s:– not

visible t

o linker

Page 91: introduction of c langauge(I unit)

CS-2303, C-Term 2010 91

Static Variable Examples (continued)

int j; //static, visible to linker & all functsstatic float f; // not visible to linker, visible to

// to all functions in this program

int fcn (float a, int b) {// nothing inside of {} is visible to linkerint i = b; //automaticdouble g; //automaticstatic double h; //static, not visible to

// linker; value retained from call to call

body – may access j, f, a, b, i, g, h

} // int fcn( … )

Note: value of h is retained

from one call to next

Value of h is also retained

across recursions

Page 92: introduction of c langauge(I unit)

CS-2303, C-Term 2010 92

Extern Variablesint j; //static, visible to linker & all functsstatic float f; // not visible to linker, visible to

// to all functions in this programextern float p; // static, defined in another program

int fcn (float a, int b) {// nothing inside of {} is visible to linkerint i = b; //automaticdouble g; //automaticstatic double h; //static, not visible to

// linker; value retained from call to call

body – may access j, f, a, b, i, g, h , p

} // int fcn( … )

extern storage class:– a

static variable defined in

another C program

Page 93: introduction of c langauge(I unit)

CS-2303, C-Term 2010 93

Extern Variables (continued)

Examples:– stdin, stdout, stderr are extern variables that

point to standard input, output, and error streams.

extern variables:– Frequently occur in .h files. Each must be actually declared outside any

function in exactly one .c file

Page 94: introduction of c langauge(I unit)

Storage class in C

Topics Automatic variables External variables Static variables Register variables Scopes and longevity of above types of

variables.

Page 95: introduction of c langauge(I unit)

Few terms

1. Scope: the scope of a variable determines over what part(s) of the program a variable is actually available for use(active).

2. Longevity: it refers to the period during which a variables retains a given value during execution of a program(alive)

3. Local(internal) variables: are those which are declared within a particular function.

4. Global(external) variables: are those which are declared outside any function.

Page 96: introduction of c langauge(I unit)

Automatic variables Are declare inside a function in which they are to be

utilized. Are declared using a keyword auto. eg. auto int number; Are created when the function is called and destroyed

automatically when the function is exited.

This variable are therefore private(local) to the function in which they are declared.

Variables declared inside a function without storage class specification is, by default, an automatic variable.

Page 97: introduction of c langauge(I unit)

Example programint main(){ int m=1000; function2(); printf(“%d\n”,m);}function1(){ int m = 10; printf(“%d\n”,m);}function2(){ int m = 100; function1(); printf(“%d\n”,m);}

Output101001000

Page 98: introduction of c langauge(I unit)

Few observation abt auto variables

Any variable local to main will normally live throughout the whole program, although it is active only in main.

During recursion, the nested variables are unique auto variables.

Automatic variables can also be defined within blocks. In that case they are meaningful only inside the blocks where they are declared.

If automatic variables are not initialized they will contain garbage.

Page 99: introduction of c langauge(I unit)

External Variables These variables are declared outside any function.

These variables are active and alive throughout the entire program.

Also known as global variables and default value is zero.

Unlike local variables they are accessed by any function in the program.

In case local variable and global variable have the same name, the local variable will have precedence over the global one.

Sometimes the keyword extern used to declare these variable.

It is visible only from the point of declaration to the end of the program.

Page 100: introduction of c langauge(I unit)

External variable (examples)int number;float length=7.5;main(){ . . . . . .}funtion1(){. . . . . .}funtion1(){. . . . . .}

int count;main(){count=10; . . . . . .}funtion(){int count=0; . . . . . . count=count+1;}

The variable number and length are available for use in all three function

When the function references the variable count, it will be referencing only its local variable, not the global one.

Page 101: introduction of c langauge(I unit)

Global variable exampleint x;int main() { x=10; printf(“x=%d\n”,x); printf(“x=%d\n”,fun1()); printf(“x=%d\n”,fun2()); printf(“x=%d\n”,fun3()); }int fun1() { x=x+10; return(x); } int fun2() { int x x=1; return(x); }

int fun3() { x=x+10; return(x); }

Once a variable has been declared global any function can use it and change its value. The subsequent functions can then reference only that new value.

Outputx=10x=20x=1x=30

Page 102: introduction of c langauge(I unit)

External declarationint main(){ y=5; . . . . . .}int y;

func1(){ y=y+1}

• As far as main is concerned, y is not defined. So compiler will issue an error message.

• There are two way out at this point1. Define y before main.2. Declare y with the storage class extern

in main before using it.

Page 103: introduction of c langauge(I unit)

Multifile Programs and extern variables

int main(){ extern int m; int i . . . . . .}function1(){ int j; . . . . . .}

file1.c

int m;function2(){ int i . . . . . .}function3(){ int count; . . . . . .}

file2.c

Page 104: introduction of c langauge(I unit)

Static Variables

The value of static variables persists until the end of the program.

It is declared using the keyword static like static int x; static float y;

It may be of external or internal type depending on the place of there declaration.

Static variables are initialized only once, when the program is compiled.

Page 105: introduction of c langauge(I unit)

Internal static variable

Are those which are declared inside a function.

Scope of Internal static variables extend upto the end of the program in which they are defined.

Internal static variables are almost same as auto variable except they remain in existence (alive) throughout the remainder of the program.

Internal static variables can be used to retain values between function calls.

Page 106: introduction of c langauge(I unit)

Examples (internal static)

Internal static variable can be used to count the number of calls made to function. eg.

int main(){ int I; for(i =1; i<=3; i++) stat(); }void stat(){ static int x=0; x = x+1; printf(“x = %d\n”,x);}

Outputx=1x=2x=3

Page 107: introduction of c langauge(I unit)

External static variables

An external static variable is declared outside of all functions and is available to all the functions in the program.

An external static variable seems similar simple external variable but their difference is that static external variable is available only within the file where it is defined while simple external variable can be accessed by other files.

Page 108: introduction of c langauge(I unit)

Static function

Static declaration can also be used to control the scope of a function.

If you want a particular function to be accessible only to the functions in the file in which it is defined and not to any function in other files, declare the function to be static. eg.

static int power(int x inty) { . . . . . . }

Page 109: introduction of c langauge(I unit)

Operators & Expressions

Page 110: introduction of c langauge(I unit)

Definition

“An operator is a symbol (+,-,*,/) that directs the computer to perform certain mathematical or logical manipulations and is usually used to manipulate data and variables”

Ex: a+b

Page 111: introduction of c langauge(I unit)

Operators in C

1. Arithmetic operators2. Relational operators3. Logical operators4. Assignment operators5. Increment and decrement operators6. Conditional operators7. Bitwise operators8. Special operators

Page 112: introduction of c langauge(I unit)

Arithmetic operators

Operator example Meaning+ a + b Addition –unary- a – b Subtraction- unary* a * b Multiplication/ a / b Division

% a % b Modulo division- remainder

Page 113: introduction of c langauge(I unit)

Relational Operators

Operator Meaning< Is less than

<= Is less than or equal to> Is greater than

>= Is greater than or equal to

== Equal to!= Not equal to

Page 114: introduction of c langauge(I unit)

Logical Operators

Operator Meaning&& Logical AND|| Logical OR! Logical NOT

Logical expression or a compound relational expression-

An expression that combines two or more relational expressions

Ex: if (a==b && b==c)

Page 115: introduction of c langauge(I unit)

Assignment operators

Syntax:v op = exp;

Where v = variable, op = shorthand assignment operator

exp = expressionEx: x=x+3

x+=3

Page 116: introduction of c langauge(I unit)

Shorthand Assignment operators

Simple assignment operator Shorthand operator

a = a+1 a + =1a = a-1 a - =1

a = a* (m+n) a * = m+n

a = a / (m+n) a / = m+n

a = a %b a %=b

Page 117: introduction of c langauge(I unit)

Increment & Decrement Operators

C supports 2 useful operators namely1. Increment ++2. Decrement – operatorsThe ++ operator adds a value 1 to the

operandThe – operator subtracts 1 from the operand++a or a++--a or a--

Page 118: introduction of c langauge(I unit)

Rules for ++ & -- operators

1. These require variables as their operands2. When postfix either ++ or – is used with the

variable in a given expression, the expression is evaluated first and then it is incremented or decremented by one

3. When prefix either ++ or – is used with the variable in a given expression, it is incremented or decremented by one first and then the expression is evaluated with the new value

Page 119: introduction of c langauge(I unit)

Examples for ++ & -- operators

Let the value of a =5 and b=++a thena = b =6Let the value of a = 5 and b=a++ thena =5 but b=6i.e.: 1. a prefix operator first adds 1 to the operand and

then the result is assigned to the variable on the left

2. a postfix operator first assigns the value to the variable on left and then increments the operand.

Page 120: introduction of c langauge(I unit)

Conditional operators

Syntax:exp1 ? exp2 : exp3Where exp1,exp2 and exp3 are expressionsWorking of the ? Operator:Exp1 is evaluated first, if it is nonzero(1/true) then the expression2 is

evaluated and this becomes the value of the expression,If exp1 is false(0/zero) exp3 is evaluated and its value becomes the

value of the expressionEx: m=2;

n=3 r=(m>n) ? m : n;

Page 121: introduction of c langauge(I unit)

Bitwise operatorsThese operators allow manipulation of data at the bit level

Operator Meaning & Bitwise AND| Bitwise OR^ Bitwise exclusive OR

<< Shift left>> Shift right

Page 122: introduction of c langauge(I unit)

Special operators

1. Comma operator ( ,)2. sizeof operator – sizeof( )3. Pointer operators – ( & and *)4. Member selection operators – ( . and ->)

Page 123: introduction of c langauge(I unit)

Arithmetic ExpressionsAlgebraic expression C expression

axb-c a*b-c

(m+n)(x+y) (m+n)*(x+y)a*b/c

3x2+2x+1 3*x*x+2*x+1a/b

S=(a+b+c)/2

cab

ba

2cba

S=

Page 124: introduction of c langauge(I unit)

Arithmetic ExpressionsAlgebraic expression C expression

area= area=sqrt(s*(s-a)*(s-b)*(s-c))

sin(b/sqrt(a*a+b*b))

tow1=sqrt((rowx-rowy)/2+tow*x*y*y)

tow1=sqrt(pow((rowx-rowy)/2,2)+tow*x*y*y)

y=(alpha+beta)/sin(theta*3.1416/180)+abs(x)

))()(( csbsass

Sin

22 ba

b

21 2

xyyx

22

1 2xyyx

xy

sin

Page 125: introduction of c langauge(I unit)

Precedence of operatorsBODMAS RULE-Brackets of Division Multiplication Addition SubtractionBrackets will have the highest precedence and have to be evaluated first, then comes of , then comes division, multiplication, addition and finally subtraction.C language uses some rules in evaluating the expressions and they r called as precedence rules or sometimes also referred to as hierarchy of operations, with some operators with highest precedence and some with least.The 2 distinct priority levels of arithmetic operators in c are-Highest priority : * / %Lowest priority : + -

Page 126: introduction of c langauge(I unit)

Rules for evaluation of expression

1. First parenthesized sub expression from left to right are evaluated.

2. If parentheses are nested, the evaluation begins with the innermost sub expression

3. The precedence rule is applied in determining the order of application of operators in evaluating sub expressions

4. The associatively rule is applied when 2 or more operators of the same precedence level appear in a sub expression.

5. Arithmetic expressions are evaluated from left to right using the rules of precedence

6. When parentheses are used, the expressions within parentheses assume highest priority

Page 127: introduction of c langauge(I unit)

Hierarchy of operators

Operator Description Associativity( ), [ ] Function call, array

element referenceLeft to Right

+, -, ++, - -,!,~,*,&

Unary plus, minus, increment, decrement, logical negation, 1’s complement, pointer reference, address

Right to Left

*, / , % Multiplication, division, modulus

Left to Right

Page 128: introduction of c langauge(I unit)

Example 1

Evaluate x1=(-b+ sqrt (b*b-4*a*c))/(2*a) @ a=1, b=-5, c=6=(-(-5)+sqrt((-5)(-5)-4*1*6))/(2*1)=(5 + sqrt((-5)(-5)-4*1*6))/(2*1)=(5 + sqrt(25 -4*1*6))/(2*1)=(5 + sqrt(25 -4*6))/(2*1)=(5 + sqrt(25 -24))/(2*1)=(5 + sqrt(1))/(2*1)=(5 + 1.0)/(2*1)=(6.0)/(2*1)=6.0/2 = 3.0

Page 129: introduction of c langauge(I unit)

Example 2

Evaluate the expression when a=4b=a- ++a

=a – 5=5-5=0