I am trying to make a C implementation of the printf function. Why does my %d specifier return
2048 - 0 - 1337-!
instead of
-2048 - 0 - -1337!
when I run
int main() {
int ret_val = my_printf("%d - %d - %d!\n", 2048, 0, -1337);
return ret_val;
}
This is my %d specifier code
{
int value = va_arg(args, int);
char buffer[32];
int index = 0;
if (value < 0)
{ //Repair this
buffer[index ] = '-';
value = -value;
}
if (value == 0)
{
buffer[index ] = '0';
}
else
{
while (value > 0)
{
buffer[index ] = '0' (value % 10);
value /= 10;
}
}
for (int i = 0; i < index / 2; i )
{
char temp = buffer[i];
buffer[i] = buffer[index - i - 1];
buffer[index - i - 1] = temp;
}
write(1, buffer, index);
size = index;
break;
}
I have tried switching these 2 lines with each
CodePudding user response:
The reason for the symptoms reported by the OP has been quickly and correctly addressed by @EricPostpischil in the comments section.
The problem with writing code from the wrong perspective is that one winds up writing far too much code. Then, lost in the fog of verbose code, patches and bandages are applied that don't quite fulfil the need.
Simply fill the 32-byte buffer from right to left, prefix the minus sign if necessary, and write the correct number of bytes to the output.
int val = va_arg( args, int );
int absVal = abs(val);
char buf[ 32 ];
int i = sizeof buf;
do buf[--i] = (char)('0' (absVal)); while((absVal/= 10) > 0);
if( val < 0 )
buf[--i] = '-';
write( 1, buf i, sizeof buf - i );
No muss, no fuss trying to reverse the array... or most of it...