Advanced pointer

361 views

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
361
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Advanced pointer

  1. 1. Pointer to FunctionsTask: Perform one of the four basic arithmetic operations specified by thecharacters +, -, * or /.// The four arithmetic operations ... one of these functions is selected// at runtime with a swicth or a function pointerfloat Plus (float a, float b) { return a+b; }float Minus (float a, float b) { return a-b; }float Multiply(float a, float b) { return a*b; }float Divide (float a, float b) { return a/b; }// Solution with a switch-statement - <opCode> specifies which operation toexecutevoid Switch(float a, float b, char opCode){ float result; // execute operation switch(opCode) { case + : result = Plus (a, b); break; case - : result = Minus (a, b); break; case * : result = Multiply (a, b); break; case / : result = Divide (a, b); break; } cout << "Switch: 2+5=" << result << endl; // display result}// Solution with a function pointer - <pt2Func> is a function pointer andpoints to// a function which takes two floats and returns a float. The functionpointer// "specifies" which operation shall be executed.void Switch_With_Function_Pointer(float a, float b, float (*pt2Func)(float,float)){ float result = pt2Func(a, b); // call using function pointer cout << "Switch replaced by function pointer: 2-5="; // display result cout << result << endl;}// Execute example codevoid Replace_A_Switch(){ cout << endl << "Executing function Replace_A_Switch" << endl; Switch(2, 5, /* + specifies function Plus to be executed */ +); Switch_With_Function_Pointer(2, 5, /* pointer to function Minus */&Minus);
  2. 2. }VOID POINTER#include <stdio.h>void use_int(void *);void use_float(void *);void greeting(void (*)(void *), void *);int main(void) { char ans; int i_age = 22; float f_age = 22.0; void *p; printf("Use int (i) or float (f)? "); scanf("%c", &ans); if (ans == i) { p = &i_age; greeting(use_int, p); } else { p = &f_age; greeting(use_float, p); } return 0;}void greeting(void (*fp)(void *), void *q) { fp(q);}void use_int(void *r) { int a; a = * (int *) r; printf("As an integer, you are %d years old.n", a);}void use_float(void *s) { float *b; b = (float *) s; printf("As a float, you are %f years old.n", *b);}

×