problem

Oct 2, 2015 at 5:19am
how to make a function parameter pass through no negative values only
Oct 2, 2015 at 7:50am
make it unsigned int. unsigned values cannot be negative.
Oct 2, 2015 at 8:17am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<stdio.h>
void add(unsigned int ,unsigned int);
int main()
{
	int a=-5,b=7;
	add(a,b);
}

void add(unsigned int aa,unsigned int bb)
{
	unsigned int c;

	c=aa+bb;

	printf("%u",c);
}



[/output]o/p=2


making parameters in function unsigned int ...does not work here... do we have to check for "minus sign before passing to the function and if its negative value reject it?[/quote]
Last edited on Oct 3, 2015 at 4:40pm
Oct 2, 2015 at 8:30am
Technically it does work. Both aa and bb are not negative.

Input should be always checked. So if OP needs that, and not what he actually asked, then yes, check for negativity is needed after input.before call.

BTW, %d is incorrect for unsigned variables. You should use %u
Last edited on Oct 2, 2015 at 8:30am
Oct 3, 2015 at 4:42pm
how to fix above problem? how to check before passing parameter to function.
Oct 3, 2015 at 7:57pm
1
2
3
4
5
6
7
8
9
int main()
{
    int a=-5,b=7;
    if(a < 0 || b < 0) {
        std::cerr << "invalid numbers\n";
        return -1;
    }    
    add(a,b);
}
Topic archived. No new replies allowed.