The L
The L

Reputation: 11

what is the difference this two type of function declaration?

I'm reading a book on data structure in C.

I saw code like this in exercise,

This is structure declaration.

typedef struct node
{
    int data;
    struct node *next;
}node;

The Function declaration, which will head of the tree..

node * create (int n);  // please explain this 

create is a function

But can we write this?

int create (int n);

Which one to use and what is the advantage of former declaration of function?

Upvotes: 0

Views: 75

Answers (3)

Blackhat002
Blackhat002

Reputation: 604

  • C allows to return a pointer from a function!

To do so, you can declare like this..

int * myFunction(int N)
{. . .}

Means it will take integer N as parameter and return a pointer of Type int.

Note :

Point to remember is that, it is not good idea to return the address of a local variable to outside of the function so you would have to define the local variable as static variable.

Like,

 int * myFunction(int N) {
 static int M[10]
 ....
 return M;
 }

Coming to your question...

node * create (int n);

Means function create will take integer parameter n and it will return a pointer to node.

So use,

  • node * create (int n); to return a pointer And
  • int create (int n); to return a integer!!

Hope it helps!!

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134336

node * create (int n);

Function is create which will accept one int argument [n] and will return a pointer to node.

int create (int n);

Function is create which will accept one int argument [n] and will return an int.

In your case, node is a typedef to a structure, clearly not an int. So, you cannot replace the first function prototype with the later one. They both have dirrerent return type. So, the comparison for advantage is pointless.

Which one to use -- depends on your need.

  1. If you want your function to return a pointer [possibly a pointer to the the newly allocated node, (in success case, or NULL in failure case)], you need to use node * create (int n); You can later use the pointer to newly allocated node in the caller function.
  2. If you want your function to return only a success or failure indication [maybe 1 and 0], then you can use int create (int n);

Upvotes: 2

Chinna
Chinna

Reputation: 3992

node * create (int n);

This function takes n as argument and returns a pointer of type node *. Here node is a structure which is defined as above and this function returns a pointer to this structure.
You should not use int as return type for this function since it is returning a pointer, not a value.

Upvotes: 0

Related Questions