Create Functions in a structure in C Programming Language (Just like classes)

Photo by Tom Claes on Unsplash


Yes, you read it right. I am talking about Creating real and working functions in a structure in C Language. This will overcome the limitations of not having functions in a structure. And the functionality of these functions is not limited. You can create any function and get it to work.

Concept Behind the Trick

Here, we are trying to implement the functionality of the class (a pillar of the OOP paradigm) in the C language structure let’s call this X.
We will define a structure, and define a signature for the function inside the structure, you can create some other variables as well.
Then, we need some real functions defined outside the structure X and assign the reference of the function to the function inside structure X.
(we will do it with examples later in this article).

Fundamentals

1. Declare & Define the function

Let’s declare the signature of the function. The function says the most common thing “Hello World!”.

2. Create the Structure

This is the most important task we need the structure.
Create a structure with the name Hello


Now, add the function that says the most common thing “Hello World!”.



Q. But, what is void (*mySayHello)();?
A. Let’s breakdown this into parts:
    Part 1 void: This is the return type that your function (mySayHello in this example) will return.
    Part 2 (*mySayHello): This is the name of the function that you will call using the structure variable. Here, we are pointing to another function using the name mySayHello.
    Part 3 (): The list of parameters if you pass.

3. Point the Function

Now, point to the function sayhello() using the function mySayHello inside the structure Hello.
Create a variable of type Hello; 


Here, assign the address of the function sayHello() to the function mySayHello();

4. Call the function

Call the function with the dot (.) operator.



Here, is the complete code download and execute.
DOWNLOAD CODE (hello_function.c)



Advanced Stuff

Add parameter list, create an initializer function, use structure variables, etc.
We will understand all with a Calculator example

1. Parameter List

That’s simply creating a function with parameter and/or return type.


 We need to pass the structure so we can access the values inside it.

Define all the functions


In place of the Calculator *c you can pass any type of variable.

The main function



2. Initializer function



Create a function MCalculator()

3. Main function

The complete code




The article was originally posted on my blog(CS111)
That’s All. 😅

Thanks for reading. 🙏
If you liked it feel free to share it with your dear ones.💗
And tell me what do you think by sending an email.💬
Stay tuned with me.
(Vikas Patel)

Post a Comment

أحدث أقدم