Click here to Skip to main content
15,888,113 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi. I was experimenting with this and I found strange behaviour which I cant understand.
Consider this code:
C++
#include "stdafx.h"

void passStructAsParam(Student s);

struct Student
{
	int rollno;
	char gender;
	int age;
};



int main()
{
	Student s; 
	s.rollno = 40;
	s.gender = 'm';
	s.age = 20;

	passStructAsParam(s);

	return 0;
}

void passStructAsParam(Student s)
{
	printf("%d \n", s.rollno);
	printf("%c \n", s.gender);
	printf("%d \n", s.age);
}

This code wont work because the structure is defined after the function declaration but if I do this:
C++
#include "stdafx.h"

void passStructAsParam(struct Student s);

struct Student
{
	int rollno;
	char gender;
	int age;
};



int main()
{
	Student s; 
	s.rollno = 40;
	s.gender = 'm';
	s.age = 20;

	passStructAsParam(s);

	return 0;
}

void passStructAsParam(struct Student s)
{
	printf("%d \n", s.rollno);
	printf("%c \n", s.gender);
	printf("%d \n", s.age);
}

This works perfectly fine. So the question here is: Why when I explecitely write that the Student is a structure in the function's parameter list it works but if i dont it doesnt ?

What I have tried:

Asking question here in CodeProject.com
Posted
Updated 17-Jul-17 2:19am
v2
Comments
Richard MacCutchan 17-Jul-17 6:42am    
What is the error that you see? Also, you should not pass complete structures as parameters, it is extremely wasteful. Pass by address or reference.

1 solution

When using the struct keyword in your function declaration you have a so called "forward declaration":
// Forward declaration
// Definition must be present later in this scope 
struct Student;

// Can now use the forward declaration within other declarations
void passStructAsParam(Student s);
 
// Final definition of structure
struct Student
{
	int rollno;
	char gender;
	int age;
};
I have moved the forward declaration out of the function declaration to explain what is happening.
 
Share this answer
 
Comments
The_Unknown_Member 17-Jul-17 8:09am    
Thanks!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900