#include<iostream>intadd(intx,inty){returnx+y;}intsubtract(intx,inty){returnx-y;}intmultiply(intx,inty){returnx*y;}intmain(){intx{};std::cout<<"Enter a number: ";std::cin>>x;inty{};std::cout<<"Enter another number: ";std::cin>>y;intop{};do{std::cout<<"Enter an operation (0=add, 1=subtract, 2=multiply): ";std::cin>>op;}while(op<0||op>2);intresult{};switch(op){// call the target function directly using early bindingcase0:result=add(x,y);break;case1:result=subtract(x,y);break;case2:result=multiply(x,y);break;}std::cout<<"The answer is: "<<result<<'\n';return0;}
#include<iostream>intadd(intx,inty){returnx+y;}intmain(){// Create a function pointer and make it point to the add functionint(*pFcn)(int,int){add};std::cout<<pFcn(5,3)<<'\n';// add 5 + 3return0;}
#include<iostream>intadd(intx,inty){returnx+y;}intsubtract(intx,inty){returnx-y;}intmultiply(intx,inty){returnx*y;}intmain(){intx{};std::cout<<"Enter a number: ";std::cin>>x;inty{};std::cout<<"Enter another number: ";std::cin>>y;intop{};do{std::cout<<"Enter an operation (0=add, 1=subtract, 2=multiply): ";std::cin>>op;}while(op<0||op>2);// Create a function pointer named pFcn (yes, the syntax is ugly)int(*pFcn)(int,int){nullptr};// Set pFcn to point to the function the user choseswitch(op){case0:pFcn=add;break;case1:pFcn=subtract;break;case2:pFcn=multiply;break;}// Call the function that pFcn is pointing to with x and y as parameters// This uses late bindingstd::cout<<"The answer is: "<<pFcn(x,y)<<'\n';return0;}