Passing structure to functions and a function returning a structure data type


Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows 2003 Server Standard Edition

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Reading and writing some data of the struct data types in C++ program example

To show: Passing struct to functions and a function returning a struct data type C++ program example




// Passing structures to functions and a function returning a structure

#include <iostream>

using namespace std;


// struct data type

struct vegetable


char name[30];

float price;



// the main program

int main(void)


// declare 2 structure variables

struct vegetable veg1, veg2;


// function prototype of type struct

struct vegetable addname();


// another function prototype

int list_func(vegetable);


// functions call for user input

veg1 = addname();

veg2 = addname();

cout<<"\nVegetables for sale\n";


// function call for data display...




return 0;



// function definitions

// This functions returns a structure

struct vegetable addname()


// normal variable

char tmp[20];


// declare a structure variable

struct vegetable vege;


// Get the size of the struct

printf("The struct vegetable size is: %d\n", sizeof(struct vegetable));

cout<<"\nEnter name of vegetable: ";


// gets(;

gets_s(, 36);

cout<<"Enter price (per 100gm): $ ";


// gets(tmp);

gets_s(tmp, 20);


// converts a string to float

vege.price = atof(tmp);

return (vege);



// structure passed from main() to function

int list_func(vegetable list)


cout<<"\nVegetable name: "<<;

cout<<"\nVegetable price: $"<<list.price;

return 0;



Output example:


The struct vegetable size is: 36

Enter name of vegetable: spinach

Enter price (per 100gm): $ 1.02

The struct vegetable size is: 36

Enter name of vegetable: potatoes

Enter price (per 100gm): $ 2.03

Vegetables for sale

Vegetable name: spinach

Vegetable price: $1.02

Vegetable name: potatoes

Vegetable price: $2.03

Press any key to continue . . .



C and C++ Programming Resources | C & C++ Code Example Index