adammenges
adammenges

Reputation: 8808

Can I declare a function without specifying a type for one of the parameters?

Can a function be defined like this:

int foo(int temp1, int temp2 temp3) {
   ...
}

Specifically with temp2 and temp3, will that cause errors? If not, what's the overall effect?

Upvotes: 0

Views: 122

Answers (7)

mu is too short
mu is too short

Reputation: 434585

If you're really trying to pass three arguments to a function but you only know the types of two of them at compile time then you can do it using a variable argument list. Suppose you want the third argument to be an int or double but you have to check temp1 or temp2 first to know which it should be:

#include <stdarg.h>

int foo(int temp1, int temp2, ...) {
    va_list ap;
    int     temp_int;
    double  temp_double;

    va_start(ap, temp2);
    /*
     * Figure out what type you want the third argument to be
     * and use va_arg(ap, int) or va_arg(ap, double) to pull
     * it off the stack.
     */
    va_end(ap);

    /*
     * Get on with what foo() is really all about (including
     * return an int.
     */
}

This sort of hack won't protect you against someone saying foo(1, 2), foo(3, 4, "fish"), or similar shenanigans but this is C and C assumes that you're grown up and responsible for your own actions.

Upvotes: 1

Demian Brecht
Demian Brecht

Reputation: 21368

You're all wrong.. This is perfectly valid with:

#define temp2 blah) { return 1; } int foo_ (int
int foo(int temp1, int temp2 temp3)
{
        return 0;
}

(This is the outcome of me feeling a little humorous first thing in the morning - feel free to downvote if you'd like to ;))

Upvotes: 5

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272457

No, that's not valid C.

Upvotes: 3

Scott C Wilson
Scott C Wilson

Reputation: 20016

What you have written is not how functions are called but rather how they are declared. You will need a datatype before each of the formal parameters (int temp1, int temp2, int temp3)

Upvotes: 0

Maged Samaan
Maged Samaan

Reputation: 1752

if emp2 and temp3 are parameters so, each of them should have its own type, but this will provide a compilation error

Upvotes: 0

Spyros
Spyros

Reputation: 48606

No it cannot. This will not work because temp3 is not really an argument. The compiler will come up with an error.

Upvotes: 0

cnicutar
cnicutar

Reputation: 182609

An error is the overall effect.

Upvotes: 3

Related Questions