5

I want to write a function prototype for a function, whose argument is a pointer to a struct.

int mult(struct Numbers *n)

However, the struct Numbers, which is defined as

struct Numbers {
    int a;
    int b;
    int c;
};

is not defined yet. How should I write a suitable prototype for mult?

2
  • 1
    You will need a forward declaration. Commented Aug 4, 2013 at 23:09
  • forward declarations only work with pointers, so if you ever want to actually pass in a struct by value, you'll need to actually fully define the struct before you use it. This is because the system knows how big a pointer is, but doesn't know how big an undefined structure is. Commented Aug 4, 2013 at 23:20

2 Answers 2

5

Just declare struct Numbers as an incomplete type before your function declaration:

struct Numbers;

int mult(struct Numbers *n);
Sign up to request clarification or add additional context in comments.

Comments

4

You must forward the declaration of the structure to tell the compiler that a struct with that name will be defined:

struct Numbers;

int mult(struct Numbers *n) {

}

struct Numbers {
    int a;
    int b;
    int c;
};

Mind that the compiler is not able to determine the size in memory of the structure so you can't pass it by value.

9 Comments

can you ever pass a struct by value in C?
@Dave absolutely. It's not normally a good idea, and you have to have the structure fully defined before you use it as a parameter, but there's nothing stopping you if you really want to.
Huh, I never knew that. I thought passing by value was C++, not C. But yeah I agree that 99% of the time it would be a really bad idea.
The thing to remember about C (and C++) is that you can do what you want, even if it's a bad idea - you just have to tell the compiler you really want to do it. Passing small, frequently created and destroyed, structs by value can reduce dynamic memory allocations, improving performance and reducing heap fragmentation.
@andy256 in that case you'd still be better off passing a pointer to a local struct. I think it would only be an advantage if the copy costs less than the dereference, which probably means the object is very very small. Maybe a complex number would be a use-case.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.