320 likes | 442 Views
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)
E N D
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 <stdio.h> • #include <stdlib.h> • 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 <stdio.h> #include <stdlib.h> 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 <stdio.h> #include <stdlib.h> 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 <stdio.h> • #include <stdlib.h> • void cleanup(); • void cleanupLast(); • void main ( ) { • char i; • atexit(cleanupLast); • atexit(cleanup); • printf("Enter a character"); • scanf("%c", &i); • }
Sample Program 8.1 #include <stdio.h> #include <stdlib.h> 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 <stdio.h> #include <stdlib.h> #include <ctype.h> 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 <stdio.h> #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 directiveMost 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 3.14 • ... • #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