Rokni Rokni - 19 days ago 5
C++ Question

c++ cout is printing wrong values

I was trying to build a

printf
function in
C++
; it worked, but when I print
int
and
float
, I get a
0
on any value I input.

#include <iostream>
#include <stdarg.h>

using namespace std;

void printf1(const char* varlist, ...)
{
int i = 0;
va_list Paramters;
va_start(Paramters, varlist);
while (varlist[i] != '\0')
{
if (varlist[i] == '%')
{
switch (varlist[i + 1])
{
case 's':
cout << va_arg(Paramters, const char*);
cout << ' ';
break;
case 'i':
cout << va_arg(Paramters, int);
cout << ' ';
break;
case 'f':
cout << va_arg(Paramters, float);
cout << ' ';
break;
}
}
++i;
}
va_end(Paramters);
cout << endl;
}

int main()
{
float f = 3.5;
printf1("%f", f);
int num = 2;
printf1("%i", num);
return 0;
}
//0
//0
//Press any key to continue . . .


Sorry for the bad spacing, but copy-pasting here is weird.

Answer

Parameters of functions that correspond to ... are promoted before passing to your variadic function. char and short are promoted to int, float is promoted to double, etc...

As a result your va_arg receives a double parameter and not a float.

change

cout << va_arg(Paramters, float);

to

cout << va_arg(Paramters, double);

and it should work just fine.

For a more detailed explanation on the topic follow this link: Variadic function (va_arg) doesn't work with float?