验证可变参数,预计类型 [英] Verifying variable arguments are of expected type

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

问题描述

我目前正在写将采取可变数量的参数的函数。我通过参数的数量成函数,然后将通过参数列表进行迭代。

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?

先谢谢您的帮助。

推荐答案

有就是你可以做到这一点没有任何合理的方式。可变参数的函数通过连接所有的原始二进制重新$ P $的参数psentations进栈上的数据一大截的工作。因此,它依赖于主叫方和被叫方商定什么参数的数量和类型都(否则到头来你会读的如 INT 就好像它是一个浮动)。

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()简直是间$ P $点的原始堆数据的字节数的一些作为任何类型您指定的宏。因此调用的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天全站免登陆