please read through the following code
#define INT 0
#define CHAR 1
#define FLOAT 2
#define DOUBLE 3
int createKey(int keySize,vector<int> &types, ...){
va_list varlist;
va_start(varlist,types.size());
int intKey;
float floatKey;
char charKey;
double doubleKey;
char *key = (char*)malloc(keySize);
int offset = 0;
for(int i=0;i<types.size();i++){
switch(types[i]){
case INT:
intKey = va_arg(varlist,int);
memcpy(&key[offset],&intKey,sizeof(int));
offset += sizeof(int);
break;
case CHAR:
charKey = va_arg(varlist,char);
memcpy(&key[offset],&charKey,sizeof(char));
offset += sizeof(char);
break;
case FLOAT:
floatKey = va_arg(varlist,float);
memcpy(&key[offset],&floatKey,sizeof(float));
offset += sizeof(float);
break;
case DOUBLE:
doubleKey = va_arg(varlist,double);
memcpy(&key[offset],&doubleKey,sizeof(double));
offset += sizeof(double);
break;
}
va_end(varlist);
}
int testIntKey;
char testCharKey;
float testFloatKey;
double testDoubleKey;
offset = 0;
for(int i=0;i<types.size();i++) {
switch(types[i]){
case INT:
memcpy(&testIntKey,&key[offset],sizeof(int));
cout<<testIntKey<<endl;
offset += sizeof(int);
break;
case CHAR:
memcpy(&testCharKey,&key[offset],sizeof(char));
cout<<testCharKey<<endl;
offset += sizeof(char);
break;
case FLOAT:
memcpy(&testFloatKey,&key[offset],sizeof(float));
cout<<testFloatKey<<endl;
offset += sizeof(float);
break;
case DOUBLE:
memcpy(&testDoubleKey,&key[offset],sizeof(double));
cout<<testDoubleKey<<endl;
offset += sizeof(double);
break;
}
}
}
In the above code, I am trying to create a key that is a combination of one or more of the datatypes(int,char,float,double)...I used ellipses as i donot know the number of arguments that may be passed to createKey(). Now the above code when compiled shows the following warnings..
varargsTest.cpp: In function ‘int createKey(int, std::vector<int, std::allocator<int> >&, ...)’:
varargsTest.cpp:20: warning: second parameter of ‘va_start’ not last named argument
varargsTest.cpp:39: warning: ‘char’ is promoted to ‘int’ when passed through ‘...’
varargsTest.cpp:39: note: (so you should pass ‘int’ not ‘char’ to ‘va_arg’)
varargsTest.cpp:39: note: if this code is reached, the program will abort
varargsTest.cpp:45: warning: ‘float’ is promoted to ‘double’ when passed through ‘...’
varargsTest.cpp:45: note: if this code is reached, the program will abort
and when i run the program with the following ..
int main()
{
vector<int> types;
types.push_back(INT);
types.push_back(CHAR);
types.push_back(INT);
createKey(9,types,85,'s',97);
}
I get Illegal instruction.
How could this problem be solved...Is this the right approach to handle these kind of problems?
operator<<likestd::ostreamdoes.va_arg(varlist, float)because the types are promoted to double; you must useva_arg(varlist, double), just like the error message says. Similarly,shortandchartypes are promoted tointand must be retrieved usingint.