开发者

c++ va_arg typecast issue

开发者 https://www.devze.com 2023-02-01 11:06 出处:网络
All, I am writing a small c++ app and have been stumped by this issue. Is there a way to create (and later catch ) the error while accessing element from va_list macro using va_arg if element type is

All,

I am writing a small c++ app and have been stumped by this issue. Is there a way to create (and later catch ) the error while accessing element from va_list macro using va_arg if element type is not expected. Eg:-

count=va_arg(argp,int); 
if (count <= 0 || count > 30)
{   
      reportParamError();   return;
}

Now, if I am passing a typedef instead of int, I get garbage value on MS compiler but 95% of time count gets value 0 on gcc (on 64 bit sles10 sys). Is there a way I can enforce some typechecking, so that I get an error that can be caught in a catch block?

Any ideas on this would be very helpful to me. Or is there a better way to do this. The function prototype is:-

 void process(App_Context * pActx, ...) 

The function is called as

 process(pAtctx,3开发者_开发技巧,type1,type2,type3);

It is essential for pActx to be passed as 1st parameter and hence cannot pass count as 1st parameter.


Update-1

Ok, this sounds strange but nargs does not seem to part of va_list on sles10 gcc. I had to put in

#ifdef _WIN32
tempCount=va_arg(argp,int)
#endif

After using this, parameters following nargs do not get garbage values. However, this introduces compiler/platform based #ifdefs....Thanks Chris and Kristopher


If you know a count will always be passed as the second argument, then you could always change the signature to this:

void process(App_Context * pActx, int count, ...) 

If that's not an option, then there is really no way to catch it. That's just how the variable-argument-list stuff works: there is no way for the callee to know what arguments are being passed, other than whatever information the caller passes.

If you look into how the va_arg macro and related macros are implemented, you may be able to figure out how to inspect all the stuff on the stack. However, this would not be portable, and it is not recommended except as a debugging aid.

You also might want to look into alternatives to variable-arguments, like function overloading, templates, or passing a vector or list of arguments.


No, there is no way. varargs doesn't provide any way to check the types of parameters passed in. You must only read them with the correct type which means that you need another way of communicating type information.

You are likely to be better off avoiding varargs functionality unless you really need it. It's only really a C++ feature for the sake of legacy functions such as printf and friends.

0

精彩评论

暂无评论...
验证码 换一张
取 消