验证变量参数是否为预期类型 [英] Verifying variable arguments are of expected type

查看:29
本文介绍了验证变量参数是否为预期类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在编写一个函数,该函数将采用可变数量的参数.我将参数的数量传递给函数,然后遍历参数列表.

I'm currently writing a function which will take a variable number of arguments. I pass the number of arguments into the function and then will iterate through the arguments list.

每个传递的参数都应该是一个整数.我将把这个整数加到一个整数向量中,稍后会用到.

Each of the passed arguments should be an integer. I will be adding this integer to a vector of integers which will be used later.

我想确保某些小丑将来不会尝试传递此函数而不是整数.我认识到我可以从 va_arg 检查当前参数以确保它不是 NULL,我可以使用类似 isanum(va_arg()) 的东西来确定它是否是一个有效的整数.我想我什至可以检查 sizeof(va_arg) 并将其与 sizeof(int) 进行比较并确保它们相等.

I would like to make sure that some joker doesn't attempt to pass this function something other then an integer in the future. I recognize that I can check the current argument from va_arg to ensure it is not NULL and I can use something like isanum(va_arg()) to determine if it is a valid integer. I suppose I could even check the sizeof(va_arg) and compare it against the sizeof(int) and ensure they are equal.

是否还有其他检查可以运行以验证我是否已传递有效整数?

Are there any other checks which I can run to verify I have been passed a valid integer?

预先感谢您的帮助

推荐答案

没有明智的方法可以做到这一点.可变参数函数的工作原理是将参数的所有原始二进制表示连接到堆栈上的一大块数据中.所以它依赖于调用者和被调用者就参数的数量和类型达成一致(否则你最终会读取例如 int 就好像它是一个 float).

There is no sensible way you can do this. Variable-argument functions work by concatenating all the raw binary representations of the arguments into one big chunk of data on the stack. So it relies on both the caller and the callee agreeing on what the number and type of arguments are (otherwise you'll end up reading e.g. an int as if it were a float).

至于您的具体想法:

  • va_arg() 是一个宏,它简单地将原始堆栈数据的一些字节解释为您指定的任何类型.因此,在其上调用 sizeof() 只会告诉您您要求的数据类型的大小.

  • va_arg() is a macro that simply interprets some number of bytes of the raw stack data as whatever type you specify. So invoking sizeof() on it will simply tell you the size of the data type you asked for.

一般来说,原始二进制数据不存在构成无效整数的模式.所以假设的 isanum() 不能工作.

In general, there are no patterns of raw binary data that form an invalid integer. So the hypothetical isanum() could not work.

这篇关于验证变量参数是否为预期类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆