Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

C Function Pointers: A Comprehensive Guide, Lecture notes of Programming Languages

A detailed explanation of C function pointers, including their declaration, usage, and an example of an array of function pointers. Students of computer science, particularly those studying programming languages, will find this document useful for understanding the concept of function pointers in C programming.

What you will learn

  • How do you declare and use a function pointer in C?
  • What is a function pointer in C?
  • What is an array of function pointers and how is it used in C?

Typology: Lecture notes

2021/2022

Uploaded on 09/12/2022

dylanx
dylanx 🇺🇸

4.7

(21)

287 documents

1 / 6

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
C Function Pointers:
The Basics
COSC 341/342:
Programming Languages, WI 2010
pf3
pf4
pf5

Partial preview of the text

Download C Function Pointers: A Comprehensive Guide and more Lecture notes Programming Languages in PDF only on Docsity!

C Function Pointers:

The Basics

COSC 341/342:

Programming Languages, WI 2010

Bottom line

A function pointer is a pointer to compiled function code.

#include <stdio.h> int addi (int x, int y) { return x+y; } int subi (int x, int y) { return x-y; } int useFunctionPtr ( int a, int b, int (* fun ) (int, int)) { return fun(a, b); } int main () { int x = 3, y = 5, result; result = useFunctionPtr (x, y, &addi); printf("%d + %d = %d\n", x, y, result); result = useFunctionPtr (x, y, &subi); printf("%d - %d = %d\n", x, y, result);

Another example, declaring & using

#include <stdio.h> #include <stdlib.h> int addi (int x, int y) { return x+y; } int subi (int x, int y) { return x-y; } int main () { int x, y, result; char op; int (func) (int, int); printf("Enter int op int, no blanks (e.g., 3+144)"); scanf("%d%c%d", &x, &op, &y); printf("You entered %d %c %d\n", x, op, y); if (op == '+') func = &addi; else if (op == '-') func = &subi; else exit(1); result = (func)(x, y); printf("%d %c %d= %d\n", x, op, y, result);

Using an array of function pointers

#include <stdio.h> int addi(int x, int y) { return x+y; } int subi(int x, int y) { return x-y; } int main () { int i, x, y, result; char op; int (funcArr[2]) (int, int); // an array of function ptrs funcArr[0] = &addi; funcArr[1] = &subi; int dataArr[4][2] = { {1, 10}, {2, 20}, {3, 30}, {4, 40}}; for (i=0; i<4; i++) { x = dataArr[i][0]; y = dataArr[i][1]; op = (i%2)? '-' : '+'; result = (funcArr[i%2])(x, y); printf("%d %c %d = %d\n", x, op, y, result); }