×

C Tutorial

C Basics

C Data Types

C Input/Output

C Operators

C Conditional Statements

C Control Statements

C Strings

C Functions

C Arrays

C Structure and Unions

C Pointers

C Preprocessor Directives

C Command-line Arguments

C File Handlings

C Graphics

C Advance Topics

C Tips and Tricks

C Important Topics

C Practice

Typedef function pointer

In this tutorial, we will learn about the typedef function and typedef function pointer in C programming language.
Submitted by Shubh Pachori, on July 11, 2022

C - typedef

The typedef is a keyword in the C to provide some meaningful and easy-to-understand names to the already existing variables. It behaves similarly as we define the alias name for any command in a C program. In simple words, we can say that this keyword redefines the name of an already existing variable.

Syntax

typedef <existing_name> <alias_name>

In the above-given syntax, the existing_name is the name of already existing variables like int, struct, char, etc. While alias_name is the new name that is given to the already existing variable.

Example of typedef

Example: Suppose we want to create a variable of type int, then it becomes a tedious task if we want to declare multiple variables of this type. To overcome the problem we use the typedef keyword.

typedef int rollno;

In the above statement, we have declared a rollno variable of type int by using the typedef keyword.

C language code for understanding usage of typedef function

#include <stdio.h>

int main()
{
    // typedef used to define rollno as
    // an int type variable
    typedef int rollno;
    // i and j are rollno type variables
    rollno i, j;

    i = 1;
    j = 2;

    printf("\nRoll no 1st:%d\t", i);
    printf("\nRoll no 2nd:%d\t", j);

    return 0;
}

Output:

Roll no 1st:1
Roll no 2nd:2

Many functions have the same signature, so we can use a function pointer to point to all these functions with the same signature. Now the function helps pass functions as arguments to other functions.

C language code for the understanding of the typedef function pointer

#include <stdio.h>

int sum(int a, int b){
    return a + b;
}

int sub(int a, int b){
    return a - b;
}

// int type function variable
typedef int function(int a, int b); 

// function type pointer variable
int callfunction(function* p, int a, int b) {
    return p(a, b);
}

int main(){
    int result;

    result = callfunction(&sum, 25, 10);

    printf("Add Result:%d\n", result);

    result = callfunction(&sub, 25, 10);

    printf("Substract Result:%d\n", result);

    return 0;
}

Output:

Add Result:35
Substract Result:15

Related Tutorials



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.