C Programming Day 3. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Storage Class Specifiers Every variable in a C.

Slides:



Advertisements
Similar presentations
Compilation and Debugging 101. Compilation in C/C++ hello.c Preprocessor Compiler stdio.h tmpXQ.i (C code) hello.o (object file)
Advertisements

C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
/* program to find area of a ring */ #include int main() { float a1,a2,a,r1,r2; printf("Enter the radius : "); scanf("%f",&r1); a1 = 3.14*r1*r1; printf("Enter.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 10: Appendices.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 13 - The Preprocessor Outline 13.1Introduction.
Guide To UNIX Using Linux Third Edition
 2000 Prentice Hall, Inc. All rights reserved. Chapter 13 - The Preprocessor Outline 13.1Introduction 13.2The #include Preprocessor Directive 13.3The.
Storage & Linkage: Effects on Scope Rudra Dutta CSC Spring 2007, Section 001.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 19 - The Preprocessor Outline 19.1 Introduction 19.2 The #include Preprocessor Directive 19.3.
Computer Science 210 Computer Organization Introduction to C.
C++ for Engineers and Scientists Third Edition
1 Further C  Multiple source code file projects  Structs  The preprocessor  Pointers.
chap13 Chapter 13 Programming in the Large.
Copyright 2001 Oxford Consulting, Ltd1 January Storage Classes, Scope and Linkage Overview Focus is on the structure of a C++ program with –Multiple.
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
Chapter 6: Modularity Using Functions. In this chapter, you will learn about: – Function and parameter declarations – Returning a single value – Returning.
MAHENDRAN CHAPTER 6. Session Objectives Explain Type of Functions Discuss category of Functions Declaration & Prototypes Explain User Defined Functions.
Macros. There are three basic phases for C programming. preprocessing, compiling, and linking. C input file is first passed to a preprocessing program.
C Tutorial Session #2 Type conversions More on looping Common errors Control statements Pointers and Arrays C Pre-processor Makefile Debugging.
Chapter 6: User-Defined Functions
1 Homework / Exam Finish up K&R Chapters 3 & 4 Starting K&R Chapter 5 Next Class HW4 due next class Go over HW3 solutions.
Functions Kernighan/Ritchie: Kelley/Pohl: Chapter 4 Chapter 5.
Chapter 13 Programming in the Large Dr. Jiung-yao Huang Dept. Comm. Eng. Nat. Chung Cheng Univ. TA: 鄭筱親 陳昱豪.
PASSING VALUE TO A FUNCTION # CALL BY VALUECALL BY VALUE # CALL BY REFERENCECALL BY REFERENCE STORAGE CLASS # AUTOAUTO # EXTERNALEXTERNAL # STATICSTATIC.
Chapter 13 C Preprocessor C How to Program, 8/e ©2016 by Pearson Education, Inc., Hoboken, NJ. All Rights Reserved.
C Hints and Tips The preprocessor and other fun toys.
Fundamentals of C and C++ Programming. EEL 3801 – Lotzi Bölöni Sub-Topics  Basic Program Structure  Variables - Types and Declarations  Basic Program.
CSCI 171 Presentation 8 Built-in Functions, Preprocessor Directives, and Macros.
C How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Preprocessing Lecture 12 April 7, 2005.
Week 2-3 Control flow (review) Conditional statements If, else, else if, switch-case, break Loop constructs for, while, do-while, break, continue, label--go;
FUNCTIONS. Funtions  The heart of effective problem solving is problem decomposition.  breaking a problem into small, manageable pieces  In C, the.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Preprocessor Midterm Review Lecture 7 Feb 17, 2004.
Compiler Directives. The C Preprocessor u The C preprocessor (cpp) changes your source code based on instructions, or preprocessor directives, embedded.
THE PREPROCESSOR
The Preprocessor Directives Introduction Preprocessing – Occurs before program compiled Inclusion of external files Definition of symbolic constants.
© Oxford University Press All rights reserved. CHAPTER 10 THE PREPROCESSOR DIRECTIVE.
1 Object-Oriented Programming -- Using C++ Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology
Adv. UNIX:pre/111 Advanced UNIX v Objectives of these slides: –look at the features of the C preprocessor Special Topics in Comp. Eng.
C PREPROCESSOR. Introduction  It is a program that processes our source program before it is passed to the compiler.  Preprocessor commands (often known.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
A First Book of ANSI C Fourth Edition
Unit 10 Code Reuse. Key Concepts Abstraction Header files Implementation files Storage classes Exit function Conditional compilation Command-line arguments.
Week 3-4 Control flow (review) Function definition Program Structures
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
Computer Science 210 Computer Organization
Chapter 13 - The Preprocessor
Functions Separate Compilation
14. THE PREPROCESSOR.
Programmazione I a.a. 2017/2018.
Pre-processor Directives
Instructor: Ioannis A. Vetsikas
User-Defined Functions
Computer Science 210 Computer Organization
Preprocessor C program → Modified C program → Object Code
Functions: Declaration, Definition, Call and return, Scope of variables, Storage classes, Recursive functions, Recursion vs Iteration.
Register Variables Declaring a variable as a "register" variable is an advisory to the compiler to keep the normal location of the variable in a register,
C Preprocessor(CPP).
CSc 352 An Introduction to the C Preprocessor
Homework Finish up K&R Chapters 3 & 4
C Preprocessor Seema Chandak.
In C Programming Language
Compiler vs linker The compiler translates one .c file into a .o file
Presentation transcript:

C Programming Day 3

2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Storage Class Specifiers Every variable in a C program has a storage class specifier –specifies how the variable is stored in the memory –governs the scope & lifetime of a variable Scope of a variable is the area within a program in which it is accessible Lifetime is the time span for which the variable is alive when the program is in execution Four storage class specifiers available in C –automatic –static –register –extern

3 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Storage Class Specifiers… automatic –automatic is the default storage class specifier. –Scope & Lifetime is within the functions in which they are declared. –auto int iCount; declares iCount as an automatic integer variable auto is a keyword and its optional

4 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Storage Class Specifiers… static –Scope of a static variable is within the function in which it is declares –Lifetime of a static variable is throughout the program i.e. static variables retain their values throughout the program –static int siCount; declares siCount as a static integer variable static is a keyword –static variables are automatically initialized to zero

5 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Storage Class Specifiers… register –Variables are stored in registers if They are frequently referenced they need to be accessed at a faster speed –Use of register variables The loop counter variables are the best candidates –Scope & Lifetime of register variables within the functions in which they are declared

6 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Storage Class Specifiers… extern –The scope of global variables is within the file in which it is declared –extern is used if a global variable defined in file1.c needs to be made available in file2.c

7 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Storage Class Specifiers… Storage AreaScopeLife TimeInitial value automaticStack Within the function Garbage externData section Across translation units Through out the program zero registerCPU register Within the function Garbage staticData section Within the function Through out the program zero Storage class

8 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Enumerated Data Types Enumeration is a list of named integer constants These constants can be used instead of the associated integer Enumerations provide self-documenting code and help in clarifying the structure of the program Example typedef enum _Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }eDays;

9 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Enumerated Data Types… Declaring a enumerated data type –eToggleSwitch is an enumeration i.e. it’s a list of 2 integer constants OFF (0) and ON(1) –TS1 is a variable of type eToggleSwitch and can have either of the values OFF (0) or ON(1) –TS1=ON will toggle the switch ON hence printf (“%d”, TS1) will print 1 –TS1=OFF will toggle the switch OFF hence printf (“%d”, TS1) will print 0 enum eToggleSwitch { OFF, ON } TS1;

Preprocessor Directives

11 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Program Life Cycle

12 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 #include int main(void ) { int iResult; scanf(“%d%d”, &a,&b); iResult = a + b; printf(“%d”, iResult); return 1; } Life Cycle Edit test.c Compile test.c Gives error, as a and b are not declared EXE not CREATED Example File: test.c

13 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 #include int main(void) { int iResult,iN1,iN2; scanf(“%d%d”, &iN1,&iN2); iResult = diff (iN1,iN2); printf(“%d”, iResult); return 1; } Life Cycle Edittest.c Compile test.c Gives error as function diff() is not declared EXE NOT CREATED Example File: test.c

14 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 #include int sum(int a, int b); int main(void) { int iResult,iN1,iN2; scanf(“%d%d”, &iN1,&iN2); iResult = sum (iN1,iN2); printf(“%d”, iResult); } Life Cycle Edit test.c Compile test.c –create object file test.o Link test.o Gives Link Error as function definition for sum() is missing EXE NOT CREATED Example File: test.c

15 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 The C Preprocessor The C Preprocessor is a program that processes the source code before it is passed to the compiler Each of these preprocessor directives begin with a # symbol The directives provided by the C Preprocessor are for –macro expansion –conditional compilation –file inclusion

16 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Macro Expansions /* file1.c */ # define PI int main (int argc, char *argv) { float fRadius, fArea; printf("\nEnter the radius of the circle:- "); scanf("%f",& fRadius); fArea =PI * fRadius * fRadius; printf("\n Area of the circle = %f", fArea); retrun 0; } /* file1.i */ # define PI int main (int argc, char *argv) { float fRadius, fArea; printf("\nEnter the radius of the circle:- "); scanf("%f",& fRadius); fArea = * fRadius * fRadius; printf("\n Area of the circle = %f", fArea); return 0; } Preprocessor

17 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Macro Expansions… Why Macros if the same can be achieved through variables? –Treating a constant as a variable is principally not correct –A variable may get altered somewhere in the program hence it no longer remains constant Advantages of Macro Expansion –The program become more readable –If the macro expansion has to be changed change only the macro definition preprocessor will replace all occurrences with the new macro expansion

18 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Macro Expansions… Macros with Arguments. # define AREA(x) (3.14 * x * x) int main (int argc, char *argv) { float fRadius, fArea; printf("\nEnter the radius of the circle:- "); scanf("%f",&fRadius); fArea =AREA(fRadius); printf("\n Area of the circle = %f", fArea); return 0; } # define AREA(x) (3.14 * x * x) int main (int argc, char *argv) { float fRadius, fArea; printf("\nEnter the radius of the circle:- "); scanf("%f",& fRadius ); fArea = 3.14 * fRadius * fRadius; printf("\n Area of the circle = %f", fArea); return 0; } Preprocessor

19 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Macro Expansions… Precautions while writing macros with arguments –Never leave a blank space between the macro template and its argument Wrong: #define ABS (iIntVarx) (3.14*iIntVarx *iIntVarx) Correct: #define ABS(iIntVarx) (3.14*iIntVarx *iIntVarx) –Parenthesize macro parameters Wrong: #define ABS(iIntVarx) iIntVarx>=0? iIntVarx :-iIntVarx Correct: #define ABS(iIntVarx) (iIntVarx)>=0? (iIntVarx) :-(iIntVarx) –Example Usage: ABS( iIntVar a-1) Translated to: iIntVar a-1>=0? iIntVar a-1: - iIntVar a-1 Required: iIntVar a-1>=0? ( iIntVar a-1): -( iIntVar a-1)

20 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Macro Expansions… Precautions while writing macros with arguments –Avoid using expressions with side effects as arguments Careful: #define ABS(i) ((i) >=0 ? (i) : (-(i)) –Example Usage: ABS(i++) Translates to: ((i++) >=0 ? (i++) : (-(i++)) –Avoid circular definitions in which the symbol being #defined appears in its own definition Wrong: #define INFINITY (INFINITY +1)

21 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Popular Usage –#define AND && –#define ARANGE (a>25 && a<50) –#define FOUND printf(“lost property”); Macro Expansions…

22 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Difference between Functions and Macros –A macro is be more generic than a function since it will accept different types of data as arguments Macros execute faster than their equivalent functions Macro Expansions…

23 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 File Inclusion Some functions are frequently required in a program Example: –printf() –scanf() These function’s prototypes can be stored in a file and it can be included in every program Such files are called as header files –“.h” extension for the files The prototypes of all related library functions are stored in a header file

24 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 File Inclusion… Preprocessor directive to include a header file –#include 2 ways to use #include 1.#include “abc.h” Preprocessor would look for the file abc.h in - the current directory - list of directories specified in the system path 2.#include Preprocessor would look for the file abc.h in - list of directories specified in the system path

25 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Difference between header files and library files A header file is a text file A typical header file contains –prototypes, –definitions –preprocessor directives –by convention it contains no program statements Header files are used by the preprocessor A library file is an object file A library file contains a –collection of compiled modules for frequently used functions Library files are used by the linker

26 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Conditional Compilation Certain circumstances might require the compiler to skip over a part of source code This can be done by the #ifdef and #endif preprocessor directives Syntax: #ifdef and #endif preprocessor directives is as follows: #ifdef macroname statement1; statement2; #endif Note: If macroname has been #defined, then the block of code between #ifdef and #endif will get compiled

27 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Example: Conditional Compilation… #define iMAX 10 int main (int argc, char *argv) { #ifdef iMAX printf(“iMAX defined "); #else printf(“iMAX not defined "); #endif return 0; }

28 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Conditional Compilation… Situations where we go for conditional compilation –To “comment out” lines of code –To make programs portable We might need to write a program which should run on different platforms. In that case certain piece of code will be platform dependent and it should be placed between a #ifdef and #endif directives

29 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 #if, #elif, #else, #endif Conditions are based on system variables, apart from the usual ones #ifdef, #ifndef Conditions test whether a symbol is defined or not #undef Undefine a symbol that was already defined #error Conditional Compilation…

30 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Example: Conditional Compilation… #define iMAX 10 int main (int argc, char *argv) { #if iMAX==10 printf(“iiMAX defined as 10"); #else printf(“iMAX not defined as 10"); #endif return 0; }

31 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Makefiles Why do we need them? –Tedious to compile each C file and then link them, especially if you have many source files What is a makefile? –Makefiles are special files used with the make utility –Helps to automatically build and manage projects with many source and header files

32 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Makefiles… A Makefile contains Dependency lines Executable command lines Macro definitions # A makefile that compiles three C files OBJECTS = try.o add.o sub.o final: $(OBJECTS) gcc $(OBJECTS) -o final add.o: add.c common.h sub.o: sub.c common.h Dependency Line Command Line Macro Definition

33 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Makefiles… /* mainfile.c */ #include main() { int iSum,iDiff; iSum=add(1,2); printf("Sum is %d\n",iSum); iDiff=sub(10,5); printf("Difference is %d\n",iDiff); } /* add.c */ #include"common.h" int add(int a, int b) { return(a+b); } /* sub.c */ #include"common.h" int sub(int a, int b) { return(a-b); } /* Common.h */ #include int add(int,int); int sub(int,int);

34 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Makefiles… # makefile to compile and execute three files # mainfile.c add.c and sub.c final: mainfile.c add.c sub.c gcc mainfile.c add.c sub.c –o final # makefile to compile and execute three files # mainfile.c add.c and sub.c OBJECTS=mainfile.o add.o sub.o final: $(OBJECTS) gcc $(OBJECTS) -o final TAB space is mandatory

35 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Makefiles… # makefile to compile and execute three files # mainfile.c add.c and sub.c OBJECTS=mainfile.o add.o sub.o final: $(OBJECTS) gcc $(OBJECTS) -o final add.o: add.c common.h sub.o: sub.c common.h

36 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Makefiles… Libraries –Compiled objects modules can be stored in a common library –Using “ar” command object modules can be grouped under a library with a common name Example: ar -r mather.lib add.o sub.o –These libraries can be used by other programs. One Library can be used by different programs

37 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Makefiles… # makefile to compile and execute three files # mainfile.c add.c and sub.c OBJECTS=mainfile.o final: $(OBJECTS) mather.lib gcc $(OBJECTS) mather.lib -o final mather.lib:add.o sub.o ar -r mather.lib add.o sub.o add.o: add.c common.h sub.o: sub.c common.h

38 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Thank You!