C Program A simple demonstration of using pointers to determine which function to use

How to write a C Program to simple demonstration of using pointers to determine which function to use in C Programming Language ?



Solution:
/*
 * A simple demonstration of using pointers
 * to determine which function to use
 *
 */

#include <stdio.h>

void printAfterCalc(int input, const char *desc, int (*func)(int input));
int shiftLeft(int input);
int shiftRight(int input);
int addSeven(int input);
int integerDivideByTwo(int input);

void main(void) {
int val = 77;

printAfterCalc(val, "Default", NULL);
printAfterCalc(val, "Bitwise shift left", shiftLeft);
printAfterCalc(val, "Bitwise shift right", shiftRight);
printAfterCalc(val, "Add seven", addSeven);
printAfterCalc(val, "Divide by 2 (integer division)", integerDivideByTwo);

getchar();
}

void printAfterCalc(int input, const char *desc, int (*func)(int input)) {
int result;

if (func)
result = func(input);
else
result = input;

printf("%s: %d\n", (desc && *desc ? desc : "No description specified"), result);
}

int shiftLeft(int input) {
return (input << 1);
}

int shiftRight(int input) {
return (input >> 1);
}

int addSeven(int input) {
return (input + 7);
}

int integerDivideByTwo(int input) {
return (input / 2);
}


Learn More :