Vivek Goel
Vivek Goel

Reputation: 24140

c making variable argument required

I have a function as

AddSprintf(char* , ... )

I want to make compile time error if somebody is calling it without two arguments. Currently if somebody is calling like

AddSprintf("hello")

it works. But I want to disable calling like this. Is there any way using g++ I can force passing of argument ?

Upvotes: 0

Views: 101

Answers (5)

iammilind
iammilind

Reputation: 69968

If you want to stick to the same name, then you can use variadic macro:

#define AddSprintf(X,...) AddSprintf(X,__VA_ARGS__)

But be very careful with this solution, as AddSprintf would work first as text replacement in preprocessing stage. Then only it would be a function.

Upvotes: 0

Marshall Conover
Marshall Conover

Reputation: 845

As 0A0D says, it's variadic - by definition, the compiler is going to be fine with it. If you want it to fail at compiler time, you may have to pull tricks - for example, if you're unit testing, have code that makes the function fail with one argument call, so that new programmers will know they can't do that.

That said, why are you trying to do this? There may be a better solution to your problem.

Upvotes: 0

user1181282
user1181282

Reputation: 766

Overload AddSprintf:

void AddSprintf(const char* , ... ) {}
void AddSprintf(const char*);

Then you get a weird error message when compiling AddSprintf("hello")

But keep in mind that with C++11 you should use variadic templates because they are typesafe.

Upvotes: 7

Some programmer dude
Some programmer dude

Reputation: 409136

You can't, really. The dots stand for "zero or more arguments", and there is no way of knowing if there is any arguments. Except maybe using assembler and do some checking of the stack pointer.

Upvotes: 0

user195488
user195488

Reputation:

What about

AddSprintf(char* , char*, ... ) 

?

Upvotes: 0

Related Questions