SlideShare a Scribd company logo
1 of 17
SC, Chen
Ch10 Program Organization
Self Study Note of K. N. King(2008) ‘C Programming A Modern Approach, 2nd Edition’
Ch10 Program Organization
10.1 Local Variables
10.2 External Variables
10.3 Blocks
10.4 Scope
10.5 Organizing a C Program
10.1 Local Variables
• A variable declared in the body of a function is said to be local to the function
• Local Variables
1. Automatic storage duration
The storage duration (or extent) of a variable is the portion of program execution during which
storage for the variable exists
Storage for a local variables is automatically
a. Allocated when the enclosing function is called
b. Deallocated when the function returns
2. Block scope
The scope of a variable is the portion of the program text in which the variable can be referenced
The local variables are visible from its point of declaration to the end of the enclosing function body
• In C99, the scope of a local variable can be very small since it doesn’t require
variable to be declared at very beginning
10.1 Local Variables: Static Local Variables
• Using keyword static in the declaration of a local variable causes
1. Static storage duration
Permanent storage duration
Retains its value throughout the execution of the program
It occupies the same memory location throughout the execution of the program
2. Still has block scope
So it’s not visible to other functions
10.1 Local Variables: Parameters
• Parameters
1. Static storage duration
2. Block scope
• Difference from local variables
Each parameter is initialized automatically when a function is called
10.2 External Variables
• External variables (Global variables) are declared outside the body of
any function
1. Static storage duration
2. File scope
It is visible from its point of declaration to the end of the enclosing file
Can be accessed by all functions that follow its declaration
10.2 External Variables
Example: Using External Variables to Implement a Stack
• Stack
An abstract concept
Like an array, can store multiple data items of the same type
Push: add it to one end
Pop: remove it from the same end
Only examine and modify an item at the top of the stack
• One way to implement stack is to store its items in an array
contents
top
10.2 External Variables: Pros and Cons of
External Variables
1. Hard to maintain
If we change an external variable during program maintenance, we’ll need to
check every function in the same file to see how the change affects it
2. Hard to identify the guilty function
If an external variable is assigned an incorrect value, it may be difficult to identity
the guilty function
3. Functions rely on external variables are hard to reuse in other program
A function depends on external variables isn’t self-contained
• Don’t use the same external variable for different purposes
• Make sure to make meaningful names
10.2 External Variables:
Guessing a Number (1/4)
/* Asks user to guess a hidden number */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_NUMBER 100
/* external variable */
int secret_number;
/* prototypes */
void initialize_number_generator(void);
void choose_new_secret_number(void);
void read_guessed(void);
int main(void)
{
char command;
printf("Guess the secret number between 1 and %d.nn", MAX_NUMBER);
initialize_number_generator();
do {
choose_new_secret_number();
printf("A new number has been chosen.n");
read_guessed();
printf("Play again? (Y/N) ");
scanf(" %c", &command);
printf("n");
} while (command == 'y' || command == 'Y');
return 0;
}
10.2 External Variables:
Guessing a Number (2/4)
/**********************************************************
* initialize_number_generator: Initializes the random *
* number generator using *
* the time of day. *
**********************************************************/
void initialize_number_generator(void)
{
srand((unsigned) time(NULL));
}
/**********************************************************
* choose_new_secret_number: Randomly selects a number *
* between 1 and MAX_NUMBER and *
* stores it in secret_number. *
**********************************************************/
void choose_new_secret_number(void)
{
secret_number = rand() % MAX_NUMBER + 1;
}
/**********************************************************
* read_guessed: Repeatedly reads user guesses and tells *
* the user whether each guess is too low, *
* too.high, or correct. When the guess is *
* correct, prints the total number of *
* guesses and returns *
**********************************************************/
void read_guessed(void)
{
int guess, num_guesses = 0;
for (;;) {
num_guesses++;
printf("ENter guess: ");
scanf("%d", &guess);
if (guess == secret_number) {
printf("You won in %d guesses!nn", num_guesses);
return;
}
else if (num_guesses < secret_number) {
printf("Too low; try again.n");
}
else {
printf("Too high; try again.n");
}
}
}
10.2 External Variables:
Guessing a Number (3/4)
/* Asks user to guess a hidden number */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_NUMBER 100
/* prototypes */
void initialize_number_generator(void);
int new_secret_number(void);
void read_guessed(int secret_number);
int main(void)
{
char command;
int secret_number;
printf("Guess the secret number between 1 and %d.nn", MAX_NUMBER);
initialize_number_generator();
do {
secret_number = new_secret_number();
printf("A new number has been chosen.n");
read_guessed(secret_number);
printf("Play again? (Y/N) ");
scanf(" %c", &command);
printf("n");
} while (command == 'y' || command == 'Y');
return 0;
}
10.2 External Variables:
Guessing a Number (4/4)
/**********************************************************
* initialize_number_generator: Initializes the random *
* number generator using *
* the time of day. *
**********************************************************/
void initialize_number_generator(void)
{
srand((unsigned) time(NULL));
}
/**********************************************************
* new_secret_number: Returns a randomly chosen number *
* between 1 and MAX_NUMBER. *
**********************************************************/
int new_secret_number(void)
{
return rand() % MAX_NUMBER + 1;
}
/**********************************************************
* read_guessed: Repeatedly reads user guesses and tells *
* the user whether each guess is too low, *
* too.high, or correct. When the guess is *
* correct, prints the total number of *
* guesses and returns *
**********************************************************/
void read_guessed(int secret_number)
{
int guess, num_guesses = 0;
for (;;) {
num_guesses++;
printf("ENter guess: ");
scanf("%d", &guess);
if (guess == secret_number) {
printf("You won in %d guesses!nn", num_guesses);
return;
}
else if (num_guesses < secret_number) {
printf("Too low; try again.n");
}
else {
printf("Too high; try again.n");
}
}
}
10.3 Blocks
• C allows compound statements to contain
declarations as well
• The body of a function is a block
• Blocks also useful inside a function body for
temporary using variables
1. Avoids cluttering the declarations at the
beginning of the function body with variables
are used only briefly
2. Reduces name conflicts
{ declarations statements }
if (i > j)
{
/* swap values of i and j */
int temp = i;
i = j
j = temp;
}
Allocated temp
Deallocated temp
Automatic storage duration
10.4 Scope (1/2)
• Scope Rule
Enable the programmer to determine which meaning is relevant at a given
point in the program
When declaration inside a block names an identifier that’s already visible, the
new declaration temporarily hides the old one, and the identifier takes on a
new meaning
− At the end of the block, the identifier regains its old meanings
10.4 Scope (2/2) int i;
void f (int i)
{
i = 1;
}
void g (void)
{
int i = 2;
if (i > 0) {
int i;
i = 0;
}
i = 4;
}
void h (void)
{
i = 5;
}
• Static storage duration
• File scope
• Automatic storage duration
• Block scope
• Automatic storage duration
• Block scope
• Automatic storage duration
• Block scope
10.5 Organizing a C Program
• Assume a program fits in to a single file, and may contain:
1. Preprocessing directives such as #include and #define
 A preprocessing directive doesn’t take effect until the line on which it appears
2. Type definitions
 A type name can’t be used until it’s been defined
3. Declarations of external variables
 A variable can’t be used until it’s declared
4. Function prototypes
5. Function definitions
 A function need to be called after defined or declared in C99
• Precede each function definition by a boxed comment that gives the name
of the function, explains its purpose, discuss the meaning of each
parameter, describes its return value, and lists any side effects it has
#include directives
#define directives
Type definitions
Declarations of external variables
Prototypes for functions other than main
Definition of main
Definitions of other functions
10.5 Organizing a C Program:
Classifying a Poker Hand
/**************************************************
********
* initialize_number_generator: Initializes the
random *
* number generator
using *
* the time of day.
*
***************************************************
*******/
void initialize_number_generator(void)
{
srand((unsigned)time(NULL));
}
/**************************************************
********
* choose_new_secret_number: Randomly selects a
number *
* between 1 and
MAX_NUMBER and *
* stores it in
secret_number. *
***************************************************
*******/

More Related Content

What's hot

Lecture20 user definedfunctions.ppt
Lecture20 user definedfunctions.pptLecture20 user definedfunctions.ppt
Lecture20 user definedfunctions.ppteShikshak
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and typesimtiazalijoono
 
Functions in c language
Functions in c language Functions in c language
Functions in c language tanmaymodi4
 
Basic structure of c programming
Basic structure of c programmingBasic structure of c programming
Basic structure of c programmingTejaswiB4
 
C language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C languageC language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C languageRakesh Roshan
 
Overview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya JyothiOverview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya JyothiSowmya Jyothi
 
Chapter 3(1)
Chapter 3(1)Chapter 3(1)
Chapter 3(1)TejaswiB4
 
C LANGUAGE - BESTECH SOLUTIONS
C LANGUAGE - BESTECH SOLUTIONSC LANGUAGE - BESTECH SOLUTIONS
C LANGUAGE - BESTECH SOLUTIONSBESTECH SOLUTIONS
 
C notes diploma-ee-3rd-sem
C notes diploma-ee-3rd-semC notes diploma-ee-3rd-sem
C notes diploma-ee-3rd-semKavita Dagar
 
Chapter 2(1)
Chapter 2(1)Chapter 2(1)
Chapter 2(1)TejaswiB4
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programmingRutvik Pensionwar
 

What's hot (20)

Lecture20 user definedfunctions.ppt
Lecture20 user definedfunctions.pptLecture20 user definedfunctions.ppt
Lecture20 user definedfunctions.ppt
 
user defined function
user defined functionuser defined function
user defined function
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
 
Functions in C
Functions in CFunctions in C
Functions in C
 
structure of a c program
structure of a c programstructure of a c program
structure of a c program
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Basic structure of c programming
Basic structure of c programmingBasic structure of c programming
Basic structure of c programming
 
C language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C languageC language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C language
 
Overview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya JyothiOverview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya Jyothi
 
Programming in c by pkv
Programming in c by pkvProgramming in c by pkv
Programming in c by pkv
 
Chapter 3(1)
Chapter 3(1)Chapter 3(1)
Chapter 3(1)
 
Function in C
Function in CFunction in C
Function in C
 
Functions in C
Functions in CFunctions in C
Functions in C
 
C LANGUAGE - BESTECH SOLUTIONS
C LANGUAGE - BESTECH SOLUTIONSC LANGUAGE - BESTECH SOLUTIONS
C LANGUAGE - BESTECH SOLUTIONS
 
Storage classess of C progamming
Storage classess of C progamming Storage classess of C progamming
Storage classess of C progamming
 
C# programs
C# programsC# programs
C# programs
 
C notes diploma-ee-3rd-sem
C notes diploma-ee-3rd-semC notes diploma-ee-3rd-sem
C notes diploma-ee-3rd-sem
 
Chapter 2(1)
Chapter 2(1)Chapter 2(1)
Chapter 2(1)
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programming
 
C language
C languageC language
C language
 

Similar to Ch10 Program Organization

What is storage class
What is storage classWhat is storage class
What is storage classIsha Aggarwal
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxKhurramKhan173
 
Storage classes, linkage & memory management
Storage classes, linkage & memory managementStorage classes, linkage & memory management
Storage classes, linkage & memory managementMomenMostafa
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptAmanuelZewdie4
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxsangeeta borde
 
Storage classes in C
Storage classes in C Storage classes in C
Storage classes in C Self employed
 
Latest C Interview Questions and Answers
Latest C Interview Questions and AnswersLatest C Interview Questions and Answers
Latest C Interview Questions and AnswersDaisyWatson5
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 FunctionDeepak Singh
 
Advanced C Programming Notes
Advanced C Programming NotesAdvanced C Programming Notes
Advanced C Programming NotesLeslie Schulte
 
OOP-Module-1-Section-4-LectureNo1-5.pptx
OOP-Module-1-Section-4-LectureNo1-5.pptxOOP-Module-1-Section-4-LectureNo1-5.pptx
OOP-Module-1-Section-4-LectureNo1-5.pptxsarthakgithub
 

Similar to Ch10 Program Organization (20)

Unit iii
Unit iiiUnit iii
Unit iii
 
Storage class
Storage classStorage class
Storage class
 
What is storage class
What is storage classWhat is storage class
What is storage class
 
C++ Functions
C++ FunctionsC++ Functions
C++ Functions
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
 
visiblity and scope.pptx
visiblity and scope.pptxvisiblity and scope.pptx
visiblity and scope.pptx
 
Storage classes, linkage & memory management
Storage classes, linkage & memory managementStorage classes, linkage & memory management
Storage classes, linkage & memory management
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.ppt
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
Storage classes in C
Storage classes in C Storage classes in C
Storage classes in C
 
User Defined Functions in C Language
User Defined Functions   in  C LanguageUser Defined Functions   in  C Language
User Defined Functions in C Language
 
C++ Constructs.pptx
C++ Constructs.pptxC++ Constructs.pptx
C++ Constructs.pptx
 
Latest C Interview Questions and Answers
Latest C Interview Questions and AnswersLatest C Interview Questions and Answers
Latest C Interview Questions and Answers
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 Function
 
Advanced C Programming Notes
Advanced C Programming NotesAdvanced C Programming Notes
Advanced C Programming Notes
 
Functions
FunctionsFunctions
Functions
 
OOP-Module-1-Section-4-LectureNo1-5.pptx
OOP-Module-1-Section-4-LectureNo1-5.pptxOOP-Module-1-Section-4-LectureNo1-5.pptx
OOP-Module-1-Section-4-LectureNo1-5.pptx
 
Functions
FunctionsFunctions
Functions
 

Recently uploaded

Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and usesDevarapalliHaritha
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacingjaychoudhary37
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 

Recently uploaded (20)

Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and uses
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacing
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 

Ch10 Program Organization

  • 1. SC, Chen Ch10 Program Organization Self Study Note of K. N. King(2008) ‘C Programming A Modern Approach, 2nd Edition’
  • 2. Ch10 Program Organization 10.1 Local Variables 10.2 External Variables 10.3 Blocks 10.4 Scope 10.5 Organizing a C Program
  • 3. 10.1 Local Variables • A variable declared in the body of a function is said to be local to the function • Local Variables 1. Automatic storage duration The storage duration (or extent) of a variable is the portion of program execution during which storage for the variable exists Storage for a local variables is automatically a. Allocated when the enclosing function is called b. Deallocated when the function returns 2. Block scope The scope of a variable is the portion of the program text in which the variable can be referenced The local variables are visible from its point of declaration to the end of the enclosing function body • In C99, the scope of a local variable can be very small since it doesn’t require variable to be declared at very beginning
  • 4. 10.1 Local Variables: Static Local Variables • Using keyword static in the declaration of a local variable causes 1. Static storage duration Permanent storage duration Retains its value throughout the execution of the program It occupies the same memory location throughout the execution of the program 2. Still has block scope So it’s not visible to other functions
  • 5. 10.1 Local Variables: Parameters • Parameters 1. Static storage duration 2. Block scope • Difference from local variables Each parameter is initialized automatically when a function is called
  • 6. 10.2 External Variables • External variables (Global variables) are declared outside the body of any function 1. Static storage duration 2. File scope It is visible from its point of declaration to the end of the enclosing file Can be accessed by all functions that follow its declaration
  • 7. 10.2 External Variables Example: Using External Variables to Implement a Stack • Stack An abstract concept Like an array, can store multiple data items of the same type Push: add it to one end Pop: remove it from the same end Only examine and modify an item at the top of the stack • One way to implement stack is to store its items in an array contents top
  • 8. 10.2 External Variables: Pros and Cons of External Variables 1. Hard to maintain If we change an external variable during program maintenance, we’ll need to check every function in the same file to see how the change affects it 2. Hard to identify the guilty function If an external variable is assigned an incorrect value, it may be difficult to identity the guilty function 3. Functions rely on external variables are hard to reuse in other program A function depends on external variables isn’t self-contained • Don’t use the same external variable for different purposes • Make sure to make meaningful names
  • 9. 10.2 External Variables: Guessing a Number (1/4) /* Asks user to guess a hidden number */ #include <stdio.h> #include <stdlib.h> #include <time.h> #define MAX_NUMBER 100 /* external variable */ int secret_number; /* prototypes */ void initialize_number_generator(void); void choose_new_secret_number(void); void read_guessed(void); int main(void) { char command; printf("Guess the secret number between 1 and %d.nn", MAX_NUMBER); initialize_number_generator(); do { choose_new_secret_number(); printf("A new number has been chosen.n"); read_guessed(); printf("Play again? (Y/N) "); scanf(" %c", &command); printf("n"); } while (command == 'y' || command == 'Y'); return 0; }
  • 10. 10.2 External Variables: Guessing a Number (2/4) /********************************************************** * initialize_number_generator: Initializes the random * * number generator using * * the time of day. * **********************************************************/ void initialize_number_generator(void) { srand((unsigned) time(NULL)); } /********************************************************** * choose_new_secret_number: Randomly selects a number * * between 1 and MAX_NUMBER and * * stores it in secret_number. * **********************************************************/ void choose_new_secret_number(void) { secret_number = rand() % MAX_NUMBER + 1; } /********************************************************** * read_guessed: Repeatedly reads user guesses and tells * * the user whether each guess is too low, * * too.high, or correct. When the guess is * * correct, prints the total number of * * guesses and returns * **********************************************************/ void read_guessed(void) { int guess, num_guesses = 0; for (;;) { num_guesses++; printf("ENter guess: "); scanf("%d", &guess); if (guess == secret_number) { printf("You won in %d guesses!nn", num_guesses); return; } else if (num_guesses < secret_number) { printf("Too low; try again.n"); } else { printf("Too high; try again.n"); } } }
  • 11. 10.2 External Variables: Guessing a Number (3/4) /* Asks user to guess a hidden number */ #include <stdio.h> #include <stdlib.h> #include <time.h> #define MAX_NUMBER 100 /* prototypes */ void initialize_number_generator(void); int new_secret_number(void); void read_guessed(int secret_number); int main(void) { char command; int secret_number; printf("Guess the secret number between 1 and %d.nn", MAX_NUMBER); initialize_number_generator(); do { secret_number = new_secret_number(); printf("A new number has been chosen.n"); read_guessed(secret_number); printf("Play again? (Y/N) "); scanf(" %c", &command); printf("n"); } while (command == 'y' || command == 'Y'); return 0; }
  • 12. 10.2 External Variables: Guessing a Number (4/4) /********************************************************** * initialize_number_generator: Initializes the random * * number generator using * * the time of day. * **********************************************************/ void initialize_number_generator(void) { srand((unsigned) time(NULL)); } /********************************************************** * new_secret_number: Returns a randomly chosen number * * between 1 and MAX_NUMBER. * **********************************************************/ int new_secret_number(void) { return rand() % MAX_NUMBER + 1; } /********************************************************** * read_guessed: Repeatedly reads user guesses and tells * * the user whether each guess is too low, * * too.high, or correct. When the guess is * * correct, prints the total number of * * guesses and returns * **********************************************************/ void read_guessed(int secret_number) { int guess, num_guesses = 0; for (;;) { num_guesses++; printf("ENter guess: "); scanf("%d", &guess); if (guess == secret_number) { printf("You won in %d guesses!nn", num_guesses); return; } else if (num_guesses < secret_number) { printf("Too low; try again.n"); } else { printf("Too high; try again.n"); } } }
  • 13. 10.3 Blocks • C allows compound statements to contain declarations as well • The body of a function is a block • Blocks also useful inside a function body for temporary using variables 1. Avoids cluttering the declarations at the beginning of the function body with variables are used only briefly 2. Reduces name conflicts { declarations statements } if (i > j) { /* swap values of i and j */ int temp = i; i = j j = temp; } Allocated temp Deallocated temp Automatic storage duration
  • 14. 10.4 Scope (1/2) • Scope Rule Enable the programmer to determine which meaning is relevant at a given point in the program When declaration inside a block names an identifier that’s already visible, the new declaration temporarily hides the old one, and the identifier takes on a new meaning − At the end of the block, the identifier regains its old meanings
  • 15. 10.4 Scope (2/2) int i; void f (int i) { i = 1; } void g (void) { int i = 2; if (i > 0) { int i; i = 0; } i = 4; } void h (void) { i = 5; } • Static storage duration • File scope • Automatic storage duration • Block scope • Automatic storage duration • Block scope • Automatic storage duration • Block scope
  • 16. 10.5 Organizing a C Program • Assume a program fits in to a single file, and may contain: 1. Preprocessing directives such as #include and #define  A preprocessing directive doesn’t take effect until the line on which it appears 2. Type definitions  A type name can’t be used until it’s been defined 3. Declarations of external variables  A variable can’t be used until it’s declared 4. Function prototypes 5. Function definitions  A function need to be called after defined or declared in C99 • Precede each function definition by a boxed comment that gives the name of the function, explains its purpose, discuss the meaning of each parameter, describes its return value, and lists any side effects it has #include directives #define directives Type definitions Declarations of external variables Prototypes for functions other than main Definition of main Definitions of other functions
  • 17. 10.5 Organizing a C Program: Classifying a Poker Hand /************************************************** ******** * initialize_number_generator: Initializes the random * * number generator using * * the time of day. * *************************************************** *******/ void initialize_number_generator(void) { srand((unsigned)time(NULL)); } /************************************************** ******** * choose_new_secret_number: Randomly selects a number * * between 1 and MAX_NUMBER and * * stores it in secret_number. * *************************************************** *******/

Editor's Notes

  1. https://www.ptt.cc/bbs/b97902HW/M.1226692638.A.F2B.html