CSCI 171 Presentation 8 Built-in Functions, Preprocessor Directives, and Macros.

Slides:



Advertisements
Similar presentations
CSCI 130 Advanced Program Control Chapter 8. Program Controls so far for loop while loop do…while loop.
Advertisements

CSCI 171 Presentation 11 Pointers. Pointer Basics.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
CS 201 Functions Debzani Deb.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 13 - The Preprocessor Outline 13.1Introduction.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 13 - The Preprocessor Outline 13.1Introduction 13.2The #include Preprocessor Directive 13.3The.
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
Functions in C. Function Terminology Identifier scope Function declaration, definition, and use Parameters and arguments Parameter order, number, and.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
 2007 Pearson Education, Inc. All rights reserved C Preprocessor.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 19 - The Preprocessor Outline 19.1 Introduction 19.2 The #include Preprocessor Directive 19.3.
By: Mr. Baha Hanene Chapter 3. Learning Outcomes We will cover the learning outcome 02 in this chapter i.e. Use basic data-types and input / output in.
Computer Science 210 Computer Organization Introduction to C.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 12 - The Preprocessor Directives (Macros)
CECS 121 EXAM 1. /* C Programming for the Absolute Beginner */ // by Michael Vine #include main() { printf(“\nC you later\n”); system(“pause”); }
Chapter 5: Data Input and Output Department of Computer Science Foundation Year Program Umm Alqura University, Makkah Computer Programming Skills
chap13 Chapter 13 Programming in the Large.
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.
CSCI 171 Presentation 1. Computer Software System Software –Operating systems –Utility programs –Language compilers Application Software.
Macros. There are three basic phases for C programming. preprocessing, compiling, and linking. C input file is first passed to a preprocessing program.
History of C 1950 – FORTRAN (Formula Translator) 1959 – COBOL (Common Business Oriented Language) 1971 – Pascal Between Ada.
Chapter 13 Programming in the Large Dr. Jiung-yao Huang Dept. Comm. Eng. Nat. Chung Cheng Univ. TA: 鄭筱親 陳昱豪.
Scanf Reads in information from the keyboard Examples –scanf(“%d”, &number); –scanf(“%d%d”, &value1, &value2); WARNINGS! –Don’t forget the & (address of)
/* C Programming for the Absolute Beginner */ // by Michael Vine #include main() { printf(“\nC you later\n”); system(“pause”); }
C Hints and Tips The preprocessor and other fun toys.
Structure of a C program Preprocessor directive (header file) Program statement } Preprocessor directive Global variable declaration Comments Local variable.
Fundamentals of C and C++ Programming. EEL 3801 – Lotzi Bölöni Sub-Topics  Basic Program Structure  Variables - Types and Declarations  Basic Program.
CECS 121 Test 1. Functions allow you to group program statements under one name C and C++ are case-sensitive so main(), MAIN(), and Main() are all different.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Functions (1)
C++ Basics C++ is a high-level, general purpose, object-oriented programming language.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Preprocessing Lecture 12 April 7, 2005.
UniMAP SemI-09/10EKT120: Computer Programming1 Week 5 – Functions (1)
CECS 130 EXAM 1. To declare a constant (read only) value: const int x = 20; const float PI = 3.14; Can we do this? const int x;
CSCI 171 Presentation 6 Functions and Variable Scope.
Khalid Rasheed Shaikh Computer Programming Theory 1.
/* C Programming for the Absolute Beginner */ // by Michael Vine #include main() { printf(“\nC you later\n”); system(“pause”); }
Compiler Directives. The C Preprocessor u The C preprocessor (cpp) changes your source code based on instructions, or preprocessor directives, embedded.
1 ICS103 Programming in C Lecture 8: Functions I.
Operating System Discussion Section. The Basics of C Reference: Lecture note 2 and 3 notes.html.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
THE PREPROCESSOR
The Preprocessor Directives Introduction Preprocessing – Occurs before program compiled Inclusion of external files Definition of symbolic constants.
1 Object-Oriented Programming -- Using C++ Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology
C PREPROCESSOR. Introduction  It is a program that processes our source program before it is passed to the compiler.  Preprocessor commands (often known.
A.Abhari CPS1251 Topic 2: C Overview C Language Elements Variable Declaration and Data Types Statement Execution C Program Layout Formatting Output Interactive.
2. C FUNDAMENTALS. Example: Printing a Message /* Illustrates comments, strings, and the printf function */ #include int main(void) { printf("To C, or.
Functions Chapter 5. Function A set of instructions that are designed to perform specific task. A complete and independent program. It is executed by.
NOTE: C programs consist of functions one of which must be main. C programs consist of functions one of which must be main. Every C program begins executing.
13 C Preprocessor.
Arithmetic Expressions
EKT120: Computer Programming
User-Written Functions
Computer Science 210 Computer Organization
Functions, Part 2 of 2 Topics Functions That Return a Value
Chapter 13 - The Preprocessor
Functions Separate Compilation
9. FUNCTIONS.
C Basics.
Pre-processor Directives
Computer Science 210 Computer Organization
Preprocessor C program → Modified C program → Object Code
CSCE 206 Lab Structured Programming in C
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 Seema Chandak.
CSCE 206 Lab Structured Programming in C
Functions, Part 2 of 3 Topics Functions That Return a Value
CPS125.
Preprocessor Directives and Macros Chapter 21
Presentation transcript:

CSCI 171 Presentation 8 Built-in Functions, Preprocessor Directives, and Macros

Built - In Functions C provides many built in functions stdio.h printf scanf math.h pow cos sin For complete list, consult ANSI guide

System functions All within stdlib.h file (must be included) exit( ) –terminates execution atexit( ) –performs functions at program termination system( ) –executes operating system commands

exit ( ) function Terminates program execution #include void main ( ) { char i; exit(0); printf("Enter a character");//These statements will scanf("%c", &i);//not be executed }

exit ( ) function continued If 0 is passed into function it means program executed normally If a nonzero value is passed into function it means program abnormally terminated (used as error code) stdlib.h has two symbolic constanst: –#define EXIT_SUCCESS 0 –#define EXIT_FAILURE 1 can call exit(EXIT_SUCCESS) can call exit(EXIT_FAILURE)

exit ( ) function continued exit( ) should only be used for abnormal termination Normal termination should occur after the last line of main is executed

Structured use of exit() #include int main(void) { float * x = NULL; x = (float *)malloc(16 * sizeof(float)); if (x == NULL) { printf("\n\n***** Memory allocation error *****"); exit(1); } //Additional program code would be put here return 0; }

Unstructured use of exit() #include void main(void) { int option = 0; printf("1. Find length"); printf("\n2. Find volume"); printf("\n3. Find area"); printf("\nPlease select an option: "); scanf("%d", &option); if (option == 1) { /*Code to find length goes here*/ } else if (option == 2) { /*Code to find volume goes here*/ } else if (option == 3) { /*Code to find area goes here*/ } else exit(0); //More code here }

atexit ( ) function Specifies one (or more) functions that are automatically executed at termination time Up to 32 functions can be registered in this way Executed in reverse order

atexit( ) function continued #include void cleanup(); void cleanupLast(); void main ( ) { char i; atexit(cleanupLast); atexit(cleanup); printf("Enter a character"); scanf("%c", &i); }

Sample Program 8.1 #include void message2(); void message1(); int main(void) { int number = 0; atexit(message2); atexit(message1); printf("\nPlease enter the number 2: "); scanf("%d", &number); if (number != 2) exit(0); else printf("You entered the correct number!"); printf("\nYou can follow directions!"); return 0; } void message2() { printf("\nPlease remember to logoff when you are done."); } void message1() { printf("\n\nThank you for using this program."); }

system ( ) function Executes operating system commands Example: system(“dir c:\\*.exe /s”); Can execute any command line system(“c:\\winnt\\system32\\notepad.exe”);

Sample Program 8.2 #include void main(void) { int option = 0; char keepGoing = 'Y'; do { printf("1. Run the Notepad application"); printf("\n2. Run the Calculator application"); printf("\n3. Display all executable files on the C drive"); printf("\n\nPlease select an option: "); scanf("%d", &option); if (option == 1) system("c:\\windows\\system32\\notepad.exe"); else if (option == 2) system("c:\\windows\\system32\\calc.exe"); else system("dir c:\\*.exe /s"); printf("\nDo you want to run the program again (Y/N)? "); scanf(" %c", &keepGoing); } while (toupper(keepGoing) == 'Y'); }

Preprocessor Part of all C compiler packages First component that processes source code Source code changed based on directives –all preprocessor directives begin with # Output - modified source code file –used in next step of compilation –deleted automatically by system

#include Imports other files into source code –maybe library functions (stdio.h) use –may be user defined functions use “ ” may have more than one function in file

Advantages of #include Structure Portability Conventions: –similar functions grouped in one file –file given descriptive name

main.c Main.c is sometimes called the driver –‘drives’ the flow of logic –often does not contain any function definitions –includes functions with #include preprocessor directive –#include “calculate.h”

#define Used for substitution macros –substituting values for variables Used for function macros –defining a function ‘on the fly’

#define - substitution macro Creates substitution macro #define PI 3.14 area = radius * radius * PI circumference = 2 * radius * PI Changes in source code after precompiling area = radius * radius * 3.14 circumference = 2 * radius * 3.14 Space after constant indicates substitution macro

#define - function macro Shorthand for a more complicated operation Arguments not type sensitive Ex: #define HALFOF(value) ((value)/2) printf(“%f”, HALFOF(x + y)); Changes in source code after precompiling printf(“%f”, ((x+y)/2)); No space after function name indicates function macro

Other function macro examples #define AVG3(a, b, c) (((a) + (b) + (c)) / 3) #define SMALLER(x, y) ((x) < (y) ? (x) : (y)) #define SUM (x, y, z) ((x) + (y) + (z))

Common Errors-function macros Spaces after function macro name –#define SUM (x, y, z) ((x) + (y) + (z)) Forgetting parenthesis –#define AREA(x, y) x*y All parameters must be used –#define SUM(x, y, z) ((x) + (y))

Sample Program 8.3 #include #define PRODUCT(x, y) x*y void main(void) { int a = 1, b = 2, c = 3, d = 4, answer = 0; answer = PRODUCT(a, b); printf("The product of %d and %d is: %d", a, b, answer); answer = PRODUCT(a+c, b+d); printf("\n\nThe product of %d and %d is: %d", a+c, b+d, answer); }

Macros vs. Functions Macros can be used for simple functions Size of program –Functions exist as a single copy –Macro expanded in code every time it is called Execution efficiency –no overhead to use a macro –overhead required for functions

#if and #endif Preprocessor directives controlling conditional compilation –if statement determines if statements executed –#if statement determines if statements compiled #elif, #else work as else if, else

Where would #if be used For purposes of CSCI 171 – building function libraries When including files –If file included more than once, code is imported for each time –out of memory –Use #if and ‘defined’ keywords to conditionally include statements for compilation –We will place all prototypes inside the appropriate.h file, and use these keywords –See ‘Process to Create.h and.c function files’ link

Function Libraries Files associated with libraries –Header files (filename.h) Include all function prototypes Include all necessary preprocessor directives Are included in the appropriate files via the #include directive –Source code files (filename.c) Include all function definitions Include the corresponding header file via the #include directive Are added to the project via the IDE (instead of being included) Detailed instructions are posted on CSCI 171 web page

Example #if #if defined mathfn_h #else #define mathfn_h //Note: no periods can be used here int areaOfSquare(int); int areaOfRectangle(int, int); #endif

Not (!) is allowed #if !defined mathfn_h #define mathfn_h int areaOfSquare(int); int areaOfRectangle(int, int); #endif

#ifndef directive Most common and structured approach #ifndef mathfn_h #define mathfn_h int areaOfSquare(int); int areaOfRectangle(int, int); #endif

#undef Opposite effect of #define #define PI #undef PI

Sample Program 8.4 View sample program 8.4 Structure the files according to the comments at the top of Program 8.4