Programming Fundamentals
Programming Fundamentals
Fundamentals
Introduction
What is Computer Science?
✦ Computation
✦ Algorithms
✦ Computer Languages
Explorations in Computing
© 2012 John S. Conery
Objectives
6
Computer Organization
Six logical units of computer system
– Input unit
Mouse, keyboard
– Output unit
Printer, monitor, audio speakers
– Memory unit
save input and processed information
– Arithmetic and logic unit (ALU)
Performs calculations
– Central processing unit (CPU)
Supervises operation of other devices
– Secondary storage unit
Hard drives, floppy drives
7
Evolution of Operating Systems
Batch processing
– One job (task) at a time
– Operating systems developed
Programs to make computers more convenient to use
Switch jobs easier
Multiprogramming
– “Simultaneous” jobs
– Timesharing operating systems
8
Algorithms
✦ The sequence of steps carried out during a computation are
defined by an algorithm
❖ an algorithm can be thought of as a “prescription”
❖ “follow these steps and you will solve your problem”
Operation Address
English-like
and easy to learn and program
Common mathematical notation
– Total Cost = Price + Tax;
– area = 5 * 5 * 3.1415;
Java, C, C++, FORTRAN, VISUAL BASIC, PASCAL
Binary Number System
Decimal
– Base 10, ten digits (0-9)
– The position (place) values are integral powers of 10: 10 0(ones),
101(tens), 102(hundreds), 103(thousands)…
– n decimal digits - 10n unique values
Binary
– Base 2, two digits (0-1)
– The position (place) values are integral powers of 2: 2 0(1), 21(2),
22(4), 23(8), 24(16), 25(32), 26(64)…
– n binary digits - 2n unique values
Big Picture
Byte = 8 bits
17
Numerical Data Types
Name Range Storage Size
simple structured
address
float double long double
pointer reference
C++ Primitive Data Types
Primitive types
integral floating
unsigned
Premitive Data Types in C/C++
Integral Types
represent whole numbers and their negatives
declared as int, short, or long
Character Types
represent single characters
declared as char
Stored by ASCII values
Boolean Type
• declared as bool
• has only 2 values true/false
• will not print out directly
Floating Types
represent real numbers with a decimal point
declared as float, or double
Scientific notation where e (or E) stand for “times 10 to the ” (.55-e6)
Data types in C
Only really four basic types:
char
int (short, long, long long, unsigned)
float
double
22
Characters (char)
In C:
23
ASCII
Special
control
character From “man ascii”:
s
| 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|
Your First Program
#include<stdio.h>
#include<conio.h>
int main()
{
printf(“Hello World : My First C language program”);
getch();
return 0;
}
Preprocessor Directives
The first two lines that begin the program are preprocessor
directives.
e.g., #include <stdio.h>
#include<conio.h>
• It isn’t a program statement
• It isn’t a part of a function body
• It does not end with a semicolon
Program statement vs preprocessor directive
Program statements are instructions to the computer to do
something, such as adding two numbers or printing a
sentence.
A preprocessor directive, on the other hand, is an
instruction to the compiler.
A part of the compiler called the preprocessor deals with
these directives before it begins the real compilation
process.
Program statement vs preprocessor directive
The preprocessor directive #include tells the
compiler to insert another file into your source
file.
The type file usually included by #include is
called a header file.
Header Files
Thepreprocessor directive #include tells the
compiler to add the file stdio to the source file
before compiling.
Why do this?
Header Files
stdio.h is an example of a header file.
It’s concerned with basic input/output operations,
and contains declarations that are needed by the
printf function.
Without these declarations, the compiler won’t
recognize printf
Always Start with main()
When you run a C\C++ program, the first
statement executed will be at the beginning of a
function called main().
The program may consist of many functions, but
on startup, control always goes to main().
If there is no function called main() in your
program, an error will be reported when you run
the program.
Functions
The parentheses following the word main are the
distinguishing feature of a function.
Without parentheses compiler would think that
main refers to some other program element.
The word int preceding the function name
indicates that this particular function has a return
value of type int.
Braces and the Function Body
The body of a function is surrounded by braces (sometimes
called curly brackets).
Every function must use this pair of braces around the
function body.
In this example there are only three statements in the
function body:
– the line starting with printf, the line starting with getch and the line
starting with return.
However, a function body can consist of many statements.
Program Statements
There are three statements in the FIRST program: the line
– printf(“Hello World: My first C++ program”);
– getch();
– and the return statement return 0;
printf
String Constants
The phrase in quotation marks, “Hello World: My first C
program”, is an example of a string constant.
Its value is set when the program is written, and it retains
this value throughout the program’s existence.
Program Statements
The first statement tells the computer to display the quoted
phrase.
A semicolon signals the end of the statement.
If you leave out the semicolon, the compiler will signal an
error.
Program Statements
getch() apart from holding the screen or waiting for a
character to be entered to exit the output screen , it also
print the input given by the user.
The last statement in the function body is return 0;
This tells main() to return the value 0 to whoever called it,
in this case the operating system or compiler. The value 0
indicates that the program had terminated successfully.
Whitespace
Compiler ignores whitespace almost completely.
Whitespace is defined as spaces, tabs and newlines.
These characters are invisible to the compiler.
You can put several statements on one line,
separated by any number of spaces or tabs, or you
can run a statement over two or more lines.
Your First Program
#include<stdio.h>
#include<conio.h>
int main()
{
printf(“Hello World : My First C language program”);
getch();
return 0;
}
#include<stdio.h>
#include<conio.h>
int main()
{
printf(“Hello World : \
My First C language program”);
getch();
return 0;
}
Exceptions to the rule
The first line of the program, starting with #include, is a
preprocessor directive, which must be written on one line.
Also, string constants, such as “Every age has a language
of its own”, cannot be broken into separate lines.
If you need a long string constant, you can insert a
backslash(\) at the line break or divide the string into two
separate strings, each surrounded by quotes.
#include<stdio.h>
#include<conio.h>
int main()
Backslash
{
printf(“Hello World : \
My First C language program”);
getch();
return 0;
}
Comments
They help the person writing a program, and anyone else
who must read the source file, understand what’s going
on.
The compiler ignores comments
Comment Syntax
Comments start with a double slash symbol (//) and terminate
at the end of the line.
#include<stdio.h>
#include<conio.h>
int main()
{
printf(“Hello World : My First C language program”); //printing a string on the monitor
getch(); //pause the application
return 0; // return 0 to operating system, that signals the program terminated
normally
}
Alternative Comment Syntax
/* this
is a
Potentially
very long
multiline
comment
*/
Ifyou attempt to use the // style comment in this case, the
closing brace won’t be visible to
the compiler-- since a // style comment runs to the end of
the line—and the code won’t compile correctly.
C/C++ Reserved words
bool const double for
return
break continue else if struct
case default enum int switch
char delete false long typedef
class do float new while
48
What is an Identifier?
• An identifier is the name to denote labels, types, variables,
constants or functions, in a C/C++ program.
• C/C++ is a case-sensitive language.
– Work is not work
Notes:
Highest precedence for NOT, AND and OR are low precedence.
Associate left to right with low precedence. Use parenthesis to override priority or for clarification
– x && y || z will evaluate “x && y ” first
– x && (y || z) will evaluate “y || z” first
Logical Operators
int age ;
bool isSenior, hasFever ;
float temperature ;
age = 20;
temperature = 102.0 ;
isSenior = (age >= 55) ; // isSenior is false
hasFever = (temperature > 98.6) ; // hasFever is true
EXPRESSION VALUE
isSenior && hasFever false
isSenior || hasFever true
!isSenior true
!hasFever false
Precedence Chart
• ++, --, !, - (unary minus), + (unary plus) Highest
• *, /, %
• + (addition), - (subtraction)
• <<, >>
• <, <=, >, >=
• ==, !=
• &&
• ||
• = Lowest
Boolean Expression (examples)
taxRate is over 25% and income is less than $20000
age is 21 or 22
Boolean Expression (examples)
(taxRate > .25) && (income < 20000)
if (Bool-Expr)
{
Statement_1
…
Statement_n
}
Use of blocks
• Denoted by { .. }
• Recommended in controlled structures (if and loop)
• Also called compound statement.
if (Bool-Expression )
{ “if clause”
}
else
{ “else clause”
}
Multiple Selection
• So far, we have only seen binary selection.
if ( age >= 18 ){
if ( age >= 18 ){ printf(“Vote!\n”) ;
printf(“Vote!\n”) ; }
} else{
printf(“Maybe next time!\n”) ;
}
Multiple Selection (con’t)
• Sometimes it is necessary to branch in more than two
directions.
• We do this via multiple selection.
• The multiple selection mechanism in C is the switch statement.
Multiple Selection with if
if (day == 0 ) { (continued)
printf (“Sunday”) ;
} if (day == 4) {
printf (“Thursday”) ;
if (day == 1 ) {
}
printf (“Monday”) ; if (day == 5) {
} printf (“Friday”) ;
if (day == 2) { }
printf (“Tuesday”) ; if (day == 6) {
} printf (“Saturday”) ;
}
if (day == 3) {
if ((day < 0) || (day > 6)) {
printf (“Wednesday”) ; printf(“Error - invalid day.\n”) ;
} }
Multiple Selection with if-else
if (day == 0 ) {
printf (“Sunday”) ;
} else if (day == 1 ) {
printf (“Monday”) ;
} else if (day == 2) { This if-else structure is more
printf (“Tuesday”) ;
} else if (day == 3) {
efficient than the corresponding if
printf (“Wednesday”) ; structure. Why?
} else if (day == 4) {
printf (“Thursday”) ;
} else if (day == 5) {
printf (“Friday”) ;
} else if (day = 6) {
printf (“Saturday”) ;
} else {
printf (“Error - invalid day.\n”) ;
}
The switch Multiple-Selection Structure
switch (expression) {
case constant1:
// code to be executed if
// expression is equal to constant1;
break;
case constant2:
// code to be executed if
// expression is equal to constant2;
break;
.
.
.
default:
// code to be executed if
// expression doesn't match any constant
}
switch Statement: Example 1
• If you have a 95, what grade will you get?
switch(int(score)/10){
case 10:
case 9: printf("Grade = A\n“); break;
case 8: printf("Grade = B\n“); break;
case 7: printf("Grade = C\n“); break;
case 6: printf("Grade = D\n“); break;
default: printf("Grade = F\n“);
}
switch Statement: Example 2
is equivalent to:
if (score >= 90)
printf(“%s”,"Grade = A\n“);
else if (score >= 80)
printf (“%s”,”Grade = B\n“);
else if (score >= 70)
printf (“%s”,"Grade = C\n“);
else if (score >= 60)
printf (“%s”,"Grade = D\n“);
else // score < 59
printf (“%s”, "Grade = F\n“);
switch Statement Details
• The last statement of each case in the switch should
almost always be a break.
• The break causes program control to jump to the closing
brace of the switch structure.
• Without the break, the code flows into the next case. This
is almost never what you want.
• A switch statement will compile without a default case,
but always consider using one.
Creating Menus
• When you want to give your user a choice on what to do next,
you can display a set of choices (a menu). The user then enters
his or her choice. You must validate the choice to make sure it
is valid before you continue the program!
Sample Program
int choice;
choice = 0;
do
{
printf( “my menu\n\n” );
printf( “1 – edit\n” );
printf( “2 – delete\n” );
printf( “3 – quit\n” );
printf( “enter your choice: “ );
scanf( “%d”, &choice );
} while ( ( choice >= 1 ) && ( choice <= 3 ) );
Sample Program (cont’d)
switch( choice )
{
case 1: printf( “Do edit\n” );
break;
case 2: printf( “Do delete\n” );
break;
case 3: printf( “Done\n” );
break;
default: printf( “Invalid choice!\n” );
break;
}
#include <stdio.h>
void main ( ) case ‘C’ :
{ case ‘c’ :
char ch ; printf(”O.K”);
printf(“ \n Enter the grade of student: \n“) ; break;
ch = getch(); case ‘D’ :
switch (ch){ case ‘d’ :
case ‘A’ :
case ‘F’ :
case ‘a’ :
case ‘f’ :
printf(”Excellent”);
printf(”poor”);
break;
case ‘B’ : break;
case ‘b’ : default:
cout<<”Good”; printf(”invalid letter grade”);
break; }
}
#include <stdio.h>
void main()
{ int x,y;
printf("Enter 2 integer number: “);
scanf(&x,&y);
switch (x+y) {
case 7: printf("Too small, sorry!“);
break;
case 5: printf("Good job!\n“);
break;
case 4: printf("Nice Pick!\n“);
case 3: printf("Excellent!\n“);
break;
case 2: printf("Masterful!\n“);
break;
case 1: printf("Incredible!\n“);
break;
default: printf("Too large!\n“);
}
printf("\n\n“);
}
Good Programming Practices
• Include a default case to catch invalid data.
• Inform the user of the type of error that has occurred
(e.g., “Error - invalid day.”).
• If appropriate, display the invalid value.
• If appropriate, terminate program execution
switch ( day )
switch Example
{
case 0:
printf (“Sunday\n”) ;
break ;
case 1:
Is this structure
printf (“Monday\n”) ; more efficient
break ; case 5: than the
case 2: printf (“Friday\n”) ;
printf (“Tuesday\n”) ; break ;
equivalent nested
break ; case 6: if-else structure?
case 3: printf (“Saturday\n”) ;
printf (“Wednesday\n”) ; break ;
break ; default:
case 4: printf (“Error -- invalid day.\n”) ;
printf (“Thursday\n”) ; break ;
break ; }
Why Use a switch Statement?
• A nested if-else structure is just as efficient as a switch
statement.
• However, a switch statement may be easier to read.
• Also, it is easier to add new cases to a switch statement than to
a nested if-else structure.
Points to Remember
• The expression followed by each case label must be a
constant expression.
• No two case labels may have the same value.
• Two case labels may be associated with the same
statements.
• The default label is not required.
• There can be only one default label, and it is usually last.
Common Programming Errors
The following if statement is true for all values of x!
Instead,use
if( 0 <= x && x <= 4)
if ( x = 10 )
printf( “ x is 10\n” );
The char Data Type
• The char data type holds a single character.
char ch;
• Example assignments:
char grade, symbol;
grade = ‘B’;
symbol = ‘$’;
• The char is held as a one-byte integer in memory. The ASCII
code is what is actually stored, so we can use them as
characters or integers, depending on our need.
The char Data Type (con’t)
• Use
scanf (“%c”, &ch) ;
to read a single character into the variable ch. (Note
that the variable does not have to be called “ch”.”)
• Use
printf(“%c”, ch) ;
to display the value of a character variable.
char Example
#include <stdio.h>
int main ( )
{
char ch ;
do
{
scanf(“%f”,&x);
if (x % 2 ==0)
break;
} while (x > 0); // exits when an even number is entered
CONTINUE Statement
allows you to skip the rest of the loop body and go back to the
beginning of the loop.
do
{
scanf(“%f”,&x);
if (x % 2 == 0)
continue;
printf(“%d\n”,x);
} while (x <100); //prints out all odd numbers entered less than 100
Program Style
• Indenting:
– Separate processes with blank lines
– Blank lines are also ignored and are used to increase readability.
– indent statements within statements (loop body)
• Comments:
– // tells the computer to ignore this line.
– for internal documentation. This is done for program clarity and to facilitate
program maintenance.
General rules for Comments
• Place a comment at the beginning of every file with the file
name, version number, a brief program description,
programmer’s name.
• Place a descriptive comment after each variable declared.
– Use a blank line before and after variable declarations
• Place a descriptive comment and a blank line before each
subtask.
Constants
• Syntax: const type identifier = value;
• Ex: const double TAX_RATE = 0.08;
• Convention: use upper case for constant ID.
Why use constants?
• Clarity: Tells the user the significance of the number. There
may be the number 0.08 elsewhere in the program, but you
know that it doesn’t stand for TAXRATE.
• Maintainability. Allows the program to be modified easily.
– Ex: Program tax compute has const double TAXRATE=0.0725. If
taxes rise to 8%, programmer only has to change the one line to
const double TAXRATE=0.08
• Safety: Cannot be altered during program execution
What is an Expression in C/C++?
• An expression is a valid arrangement of variables, constants,
and operators.
• In C++, each expression can be evaluated to compute a value of
a given type
starting = count + 5;
• Expression evaluation:
– Get value of count: 0
– Add 5 to it.
– Assign to starting 5
//********************************************************
// Program Convert Measurements: This program converts
// measurements in feet and inches into centimeters using
// the formula that 1 inch is equal to 2.54 centimeters.
//********************************************************
#include <condio.h>
#include <stdio.h>
//named constants
const double CENTIMETERS_PER_INCH = 2.54;
const int INCHES_PER_FOOT = 12;
int main ()
{
//declare variables
int feet, inches;
int totalInches;
double centimeter;
//Statements: Step 1 - Step 7
printf("Enter two integers, one for feet and "one for inches: “);
//Step 1
printf("For Feet: ");
scanf("%d",&feet);
printf("For inches: ");
scanf("%d", &inches);
//Step 2
printf("The Numbers you entered are %d ", feet);
printf("for feet, and %d for inches. ", inches);
//Step 3
totalInches = INCHES_PER_FOOT * feet + inches;
//Step 4
printf(“The total number of inches = %f“, totalInches,”\n);
//Step 5
centimeter = CENTIMETERS_PER_INCH * totalInches;
//Step 6
printf("\nThe total number of inches = %d", totalInches);
//Step 7
return 0;
}
Sample Run
Enter two integers, one for feet, one for inches: 15 7
The numbers you entered are 15 for feet and 7 for inches.
The total number of inches = 187
The number of centimeters = 474.98
Operators
Pre- and post-variations of ++ and –– operators
Abbreviated (compound) assignment expressions
• n –= 5; /* is equivalent to n = n – 5; */
• n *=5; /* is equivalent to n = n * 5; */
• n /= 5; /* is equivalent to n = n / 5; */
• n %= 5; /* is equivalent to n = n % 5; */
Logical Operators in C
• Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };
− If not enough initializers, rightmost elements become 0
− If too many initializers, a syntax error is generated
int n[ 5 ] = { 0 }
− Sets all the elements to 0
• If size omitted, the initializers determine it
int n[] = { 1, 2, 3, 4, 5 };
− 5 initializers, therefore n is a 5 element array
Multiple-Subscripted Arrays
• Multiple subscripts - tables with rows, columns
− Like matrices: specify row, then column.
Column 0 Column 1 Column 2 Column 3
Row 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]
Row 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]
Row 2 a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]
Column subscript
Array name
Row subscript
1 2
• Initialize 3 4
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
FIGURE 11-3 Storing Strings
132
FIGURE 11-8 String Literal References
134
Note
Memory for strings must be allocated before the
string can be used.
135
FIGURE 11-10 Initializing Strings
136
Changing String Variables (cont)
• Can change parts of a string variable
char str1[6] = “hello”;
str1[0] = ‘y’;
/* str1 is now “yello” */
str1[4] = ‘\0’;
/* str1 is now “yell” */
• Important to retain delimiter (replacing str1[5] in the original
string with something other than ‘\0’ makes a string that does
not end)
• Have to stay within limits of array
Memory Storage for a String
[0] [13]
I n i t i a l v a l u e \0 ? ? …
9-138
Input/Output of a String
• The placeholder %s is used to represent string arguments in printf
and scanf.
− printf(“Topic: %s\n”, string_var);
• The string can be right-justified by placing a positive number in
the placeholder.
− printf(“%8s”, str);
• The string can be left-justified by placing a negative number in the
placeholder.
− Printf(“%-8s”, str);
9-139
Right and Left Justification of Strings
The “%8s” placeholder displays a string which is right-justified and in 8-
columns width.
If the actual string is longer than the width, the displayed field is expanded
with no padding.
9-140
Input/Output of a String
• The placeholder %s is used to represent string arguments in
printf and scanf.
− printf(“Topic: %s\n”, string_var);
• The string can be right-justified by placing a positive number in
the placeholder.
− printf(“%8s”, str);
• The string can be left-justified by placing a negative number in
the placeholder.
− Printf(“%-8s”, str);
9-141
Right and Left Justification of Strings
The “%8s” placeholder displays a string which is right-justified and in 8-
columns width.
If the actual string is longer than the width, the displayed field is expanded
with no padding.
9-142
An Example of Manipulating String with scanf
and printf
9-143
Execution of scanf ("%s", dept);
• Whenever encountering a white space, the scanning stops and scanf places the null character
at the end of the string.
• e.g., if the user types “MATH 1234 TR 1800,” the string “MATH” along with ‘0’ is stored into dept.
9-144
String Library Functions
9-145
Some String Functions from String.h
Function Purpose Example
strcpy Makes a copy of a string strcpy(s1, “Hi”);
strcat Appends a string to the end of strcat(s1, “more”);
another string
strcmp Compare two strings alphabetically strcmp(s1, “Hu”);
9-148
Extracting Substring of a String (2/2)
• e.g., strncpy(result, &s1[5], 2);
9-149
Functions strcat and strlen
• Functions strcat and strncat concatenate the fist
string argument with the second string argument.
− strcat(dest, “more..”);
− strncat(dest, “more..”, 3);
• Function strlen is often used to check the length of a
string (i.e., the number of characters before the fist null
character).
− e.g., dest[6] = “Hello”;
strncat(dest, “more”, 5-strlen(dest));
dest[5] = ‘\0’;
9-150
Distinction Between Characters and Strings
• The representation of a char (e.g., ‘Q’) and a string (e.g., “Q”) is
essentially different.
− A string is an array of characters ended with the null character.
Q Q \0
9-151
String Comparison (1/2)
• Suppose there are two strings, str1 and str2.
− The condition str1 < str2 compare the initial memory address
of str1 and of str2.
• The comparison between two strings is done by comparing each
corresponding character in them.
− The characters are comapared against the ASCII table.
− “thrill” < “throw” since ‘i’ < ‘o’;
− “joy” < joyous“;
• The standard string comparison uses the strcmp and strncmp
functions.
9-152
String Comparison (2/2)
9-153
Input/Output of Characters and Strings
• The stdio library provides getchar function which
gets the next character from the standard input.
− “ch = getchar();” is the same as “scanf(“%c”,&ch);”
− Similar functions are putchar, gets, puts.
9-154
Character Analysis and Conversion
• The <ctype.h> library defines facilities for character analysis and
conversion.
Functions Description
isalpha Check if the argument is a letter
9-156
Static Data Allocation
Auto
matic
h er e array
u po n s allo
entry cated
to blo
0xFFFFFFFF ck.
stack
(dynamically allocated)
SP
heap
address space (dynamically allocated)
static data
program code
PC
0x00000000 (text)
Arrays in C
157
Data Storage in Memory
• Variables may be automatic or static
158
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
159
Example
int fcn (float a, int b) { i is visible from this point
int i; to end of fcn
g is visible from this point
double g; to end of fcn
161
Static Data – Very different
• Static variables may be declared within or outside of functions
• Storage allocated when program is initialized
• Storage is released when program exits
• Compiler sets aside storage for all static variables at compiler or link
time
• Values retained across function calls
162
Static Variable Examples
int j; //static, visible to linker & all functs
static float f; // not visible to linker, visible to
// to all functions in this program
} // int fcn( … )
163
Static Variable Examples (continued)
int j; //static, visible to linker & all functs
static float f; // not visible to linker, visible to
// to all functions in this program
De
cla
f rati
int fcn (float a, int b) { u nct o n o
st ion uts
// nothing inside of {} is visible to linker at :– a ide a
vis
ic lwa ny
int i = b; //automatic
ible s to y s st
r ag atic
double g; //automatic to l e c
ink lass:
static double h; //static, not visible to er –n
ot
// linker; value retained from call to call
} // int fcn( … )
} // int fcn( … )
} // int fcn( … )
CS-2303, C-Term 2010
Scope Rules and Storage Types 167
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