[Info-vax] VMS Cobol - GnuCOBOL

Dan Cross cross at spitfire.i.gajendra.net
Wed Mar 1 14:30:49 EST 2023


In article <k69hofFu2e4U2 at mid.individual.net>,
bill  <bill.gunshannon at gmail.com> wrote:
>On 2/28/2023 2:11 PM, Dan Cross wrote:
>> 
>> 
>> Consider, for example, this segment of code:
>> 
>> unsigned short
>> mul(unsigned short a, unsigned short b)
>> {
>> 	return a * b;
>> }
>
>I have always considered this to be really stupid code.
>For the vast majority of values for a and b this is going to
>overflow.  That means that regardless of what "undefined behavior"
>actually means the result will be useless.

?? Sure, this is a contrived example, but what makes you think
that the original programmer didn't want the wrapping behavior
on overflow?

It's a contrived example, but having well-defined overflow
semantics is actually really useful; consider checksumming
and hashing functions.  Or, for that matter, cryptographic
code (which often makes heavy use of modular arithmetic).

Yeah, this example is dumb, but there are plenty of similar
examples that are not.  For example, consider this checksum:

unsigned char
checksum(const unsigned char *p, size_t n)
{
	unsigned char c = 0;

	for (size_t i = 0; i < n; i++)
		c += *p++;

	return 0 - c;
}

Is that well-defined?  One may look at it and say, "yes, of
course; there's no way that the addition can overflow because
both 8-bit `unsigned char` operands will be converted to any
flavor of `int`, and that cannot overflow."

Except that there are implementations where the range of `int`
and `unsigned char` are the same, and on those, overflow _could_
occur.

So, one should, instead, write:

unsigned char
checksum(const unsigned char *p, size_t n)
{
	unsigned int c = 0;

	for (size_t i = 0; i < n; i++)
		c += *p++;

	return 0 - c;
}

Subtle, no?

>What were we just saying about programmers not writing buggy code?

Good luck with that.  :-)

	- Dan C.




More information about the Info-vax mailing list