[LCP]sign problem

Erik Mouw J.A.K.Mouw at ITS.TUDelft.NL
Fri Aug 10 09:22:05 UTC 2001


On Wed, Aug 08, 2001 at 08:41:59PM +0530, Srinath Thiruvengadam wrote:
> in one of my programs , i used an unsigned int variable.
> i had a problem in this program. 
> 
> i traced the execution and  found that in one place 
> a negative value goes into the variable.
> 
> howz that possible? shouldnt the program end
> abnormally on receiving a signed number???

No. C allows you to assign signed integers to unsigned integers.
Nothing wrong with that, it's the programmers responsibility to check
for ranges. That's why you should *always* use assert(), like this:

	int foo(int bar)
	{
		unsigned int gnu;

		assert(bar >= 0);

		gnu = bar;

		/* ... */
	}

In this way you will get a runtime error whenever bar < 0:

	foo: foo.c:5: foo: Assertion `bar >= 0' failed

Asserts are best built in your code at the moment your write a
function, because at that time you know what the valid input ranges
are.

> and when i print the number the no. prints as a 
> negative number. i thought the signed would not 
> be used for unsigned variables.

If you tell printf() that the variable is a signed integer, and you put
an unsigned integer on the stack it (sort of) works like a typecast:
printf() will just interpret it as a signed integer.

Erik

-- 
J.A.K. (Erik) Mouw, Information and Communication Theory Group, Department
of Electrical Engineering, Faculty of Information Technology and Systems,
Delft University of Technology, PO BOX 5031,  2600 GA Delft, The Netherlands
Phone: +31-15-2783635  Fax: +31-15-2781843  Email: J.A.K.Mouw at its.tudelft.nl
WWW: http://www-ict.its.tudelft.nl/~erik/



More information about the linuxCprogramming mailing list