Home » C programs » C Structure & Union programs

C program for passing structures as function arguments and returning a structure from a function

This program will demonstrate example for passing Structures as function arguments and returning a structure from a function in C language.

Structures can be passed as function arguments.

We can have a function of type returning a structure or a pointer to it, below code shows how to operate when we have a function taking structure as an argument:

Passing structure in function and returning structure from function program in C

#include <stdio.h>

//Lets create a structure first
struct FirstStruct
{
	int Num1;
	int Num2;
}FirstStruct_IP;

//function declarations
struct FirstStruct TakeUserInput(void);
void DisplayOutput(struct FirstStruct Input);

//structure object declaration
struct FirstStruct inputStruct;

int main()
{
    //create a structure to get a return from TakeUserInput function
    //Now use the DisplayOutput to print the input
    DisplayOutput(TakeUserInput());
	
	return 0;
}

//This function returns a structure after storing the user input into it
struct FirstStruct TakeUserInput(void)
{

    printf("Enter a number: ");
    scanf("%d",&inputStruct.Num1);
    printf("Enter a number again: ");
    scanf("%d",&inputStruct.Num2);

    return inputStruct;
}
//Function taking Structure as argument
void DisplayOutput(struct FirstStruct Input)
{
    printf("%d\n",((Input.Num1)+(Input.Num2)));
}

Output

Enter a number: 10
Enter a number again: 20
30





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.