CSCI 171

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

description

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) - PowerPoint PPT Presentation

Transcript of CSCI 171

Page 1: CSCI 171

CSCI 171

Presentation 8

Built-in Functions, Preprocessor Directives, and Macros

Page 2: CSCI 171

Built - In Functions

• C provides many built in functions

• stdio.h printf scanf

• math.h pow cos sin

• For complete list, consult ANSI guide

Page 3: CSCI 171

System functions

• All within stdlib.h file (must be included)

• exit( )– terminates execution

• atexit( )– performs functions at program termination

• system( )– executes operating system commands

Page 4: CSCI 171

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 }

Page 5: CSCI 171

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)

Page 6: CSCI 171

exit ( ) function continued

• exit( ) should only be used for abnormal termination

• Normal termination should occur after the last line of main is executed

Page 7: CSCI 171

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;}

Page 8: CSCI 171

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*/ }elseif (option == 2) {/*Code to find volume goes here*/ }elseif (option == 3) {/*Code to find area goes here*/ }else exit(0);//More code here

}

Page 9: CSCI 171

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

Page 10: CSCI 171

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); }

Page 11: CSCI 171

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);

elseprintf("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.");

}

Page 12: CSCI 171

system ( ) function

• Executes operating system commands

• Example: system(“dir c:\\*.exe /s”);

• Can execute any command line system(“c:\\winnt\\system32\\notepad.exe”);

Page 13: CSCI 171

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');

}

Page 14: CSCI 171

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

Page 15: CSCI 171

#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

Page 16: CSCI 171

Advantages of #include

• Structure

• Portability

• Conventions:– similar functions grouped in one file– file given descriptive name

Page 17: CSCI 171

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”

Page 18: CSCI 171

#define

• Used for substitution macros– substituting values for variables

• Used for function macros– defining a function ‘on the fly’

Page 19: CSCI 171

#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

Page 20: CSCI 171

#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

Page 21: CSCI 171

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))

Page 22: CSCI 171

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))

Page 23: CSCI 171

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);

}

Page 24: CSCI 171

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

Page 25: CSCI 171

#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

Page 26: CSCI 171

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

Page 27: CSCI 171

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

Page 28: CSCI 171

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

Page 29: CSCI 171

Not (!) is allowed

#if !defined mathfn_h

#define mathfn_h

int areaOfSquare(int);

int areaOfRectangle(int, int);

#endif

Page 30: CSCI 171

#ifndef directiveMost common and structured

approach

#ifndef mathfn_h

#define mathfn_h

int areaOfSquare(int);

int areaOfRectangle(int, int);

#endif

Page 31: CSCI 171

#undef

• Opposite effect of #define #define PI 3.14 ... #undef PI

Page 32: CSCI 171

Sample Program 8.4

• View sample program 8.4

• Structure the files according to the comments at the top of Program 8.4