ShadyBears
ShadyBears

Reputation: 4185

What is this C program doing? Integer Arithmetic**

It is returning 1 despite what the values of x and y are. I'm not understanding how or why. I copied a program from my textbook so this isn't something I wrote. We are currently studying integer arithmetic.

Can someone please explain what this code is doing? Thank you!

#include <stdio.h>

int uadd_ok(unsigned x, unsigned y)
{
unsigned sum = x+y;
return sum >=y;
}

int main(int argc, char** argv) 
{ 
int x = 1, y = 5;

printf("Answer is: %d\n", uadd_ok(x,y));
    return 0;
}

Upvotes: 0

Views: 162

Answers (2)

matt
matt

Reputation: 1983

Since x and y are unsigned, they are both positive. The sum of x and y therefore has to be greater than y. So sum >= y is true, which gets converted to 1 because you formatted it as %d.

Upvotes: 2

Kerrek SB
Kerrek SB

Reputation: 477444

The expression sum >= y is a boolean, and thus it gets converted to either 0 or 1 depending on its value. Since x and y are unsigned, assuming there's no overflow you will always have x + y >= y, so the result is always true, and thus 1.

(Presumably the point of the function is to check whether an overflow occurred...)

Upvotes: 3

Related Questions