introduction of c langauge(i unit)
TRANSCRIPT
MAHARSHI ARVIND INSTITUTE OF ENGINEERING TECHNOLOGY, JAIPUR
B.TECH II SEM
FUNDAMENTAL OF COMPUTER PROGRAMMING
Presented by
Er. PRASHANT KUMAR SHARMA( CSE DEPT)
Unit-1
INTRODUCTION
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.
C Preprocessor Overview Preprocessor Directives Conditional Compilation Predefined Symbolic Constants
Overview Six phases to execute C:
1. Edit2. Preprocess3. Compile4. Link5. Load6. Execute
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
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
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
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
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
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
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
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 (;)
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
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
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 ) );
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
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
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 #
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").
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
executableprogram
Eclipse
debugger
precompiler
compiler
link
turnin/checkin
An “IDE”WebCAT
Visual Studio
window
compile
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.
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.
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.
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
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 ; }
Anatomy of a C Program program header comment
preprocessor directives (if any)
int main ( ) { statement(s) return 0 ; }
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.
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.
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.
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.
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.
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
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 */
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.
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.
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.
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.
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
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.
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
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.
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.
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.
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.
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.
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.
48
Compilation Details
object.h
object.cpp
main.cpp
object.s
main.s
object.o
main.o
Output
Source code Assembly Machine Code
Simple Data Types in C
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
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
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
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
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 = ’\\’;
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
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!
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)
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?
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
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, …
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
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
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:
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:
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? ?
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
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
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
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
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
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
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
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
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"!
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
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
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”
Enumeration Type (continued)
The syntax for enumeration type is:
value1, value2, … are identifiers called enumerators
value1 < value2 < value3 <...
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
Scope Rules and Storage Types
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.
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
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!
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
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( … )
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
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
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
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
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
Storage class in C
Topics Automatic variables External variables Static variables Register variables Scopes and longevity of above types of
variables.
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.
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.
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
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.
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.
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.
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
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.
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
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.
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.
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
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.
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) { . . . . . . }
Operators & Expressions
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
Operators in C
1. Arithmetic operators2. Relational operators3. Logical operators4. Assignment operators5. Increment and decrement operators6. Conditional operators7. Bitwise operators8. Special operators
Arithmetic operators
Operator example Meaning+ a + b Addition –unary- a – b Subtraction- unary* a * b Multiplication/ a / b Division
% a % b Modulo division- remainder
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
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)
Assignment operators
Syntax:v op = exp;
Where v = variable, op = shorthand assignment operator
exp = expressionEx: x=x+3
x+=3
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
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--
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
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.
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;
Bitwise operatorsThese operators allow manipulation of data at the bit level
Operator Meaning & Bitwise AND| Bitwise OR^ Bitwise exclusive OR
<< Shift left>> Shift right
Special operators
1. Comma operator ( ,)2. sizeof operator – sizeof( )3. Pointer operators – ( & and *)4. Member selection operators – ( . and ->)
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=
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
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 : + -
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
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
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
Example 2
Evaluate the expression when a=4b=a- ++a
=a – 5=5-5=0