0
votes

I'm curious why the following code returns negative numbers even though every single variable and fuction initialization in this program is an unsigned int. I thought they always were supposed to be positive?.

#include <stdio.h>

unsigned int main ()
{
unsigned int ch = 0;
unsigned int asteriskValue = 0;
while(ch!=27)
{
    ch = getch();
        if (ch == 224)
        {
            increaseDecrease(&asteriskValue);
        }
    printf("%d",asteriskValue);
}
}

void increaseDecrease(unsigned int *value)
{
unsigned int upOrDown;
upOrDown = getch ();
if(upOrDown == 72)
    (*value)--;
else if(upOrDown == 80)
    (*value)++;
}
1
unsigned integers are not only positive, but can also be 0. Using The wrong format-specifier invokes undefined behaviour.too honest for this site
unsigned is not a trait, but a type specifier. C does not support traits.too honest for this site

1 Answers

1
votes

I think your results is really a positive value, but printing it with a "%d" flag, tells printf to interpret it as a signed value, as if you were casting on the fly the type: (signed)asteriskValue

Try printing it with a "%u" formatting instead of "%d".