Skip to content

Instantly share code, notes, and snippets.

@yorkie
Last active December 11, 2015 18:38
Show Gist options
  • Save yorkie/4642890 to your computer and use it in GitHub Desktop.
Save yorkie/4642890 to your computer and use it in GitHub Desktop.
无符号数与有符号数常常出现在程序中的代码失误(一)
/*
* code来自《深入理解计算机系统》Page-52
* The below function which called within sum_element(arr, 0) will occur a RAM's trouble to you
* should be invoked within 2 arguments, an array and a unsigned integer "length".
*
* Analysis:
* If the argument length is assigned with ZERO, namely return 0.0 under human's comprehension.
* As an opposite ending, however in fact, length is unsigned. Such that length-1 will be treated
* as length+((unsigned)(-1)), UMax. Even worse is the logical operator "<", whose operands are the
* unsigned integer UMax and an integer i, it always return true - !
* All right, the reason is found. RAM is occured with an overflow.
*
*/
float sum_element(float arr[], unsigned length)
{
int i;
float result;
for (i=0; i<=length-1; i++) {
result += a[i];
};
return result;
}
/* Here is a correct version */
float sum_element_v1(float arr[], unsigned length)
{
int i;
float result;
if (length == 0) { // if length is 0, return 0.0
return 0.0;
}
for (i=0; i<=length-1; i++) {
result += a[i];
};
return result;
}
/* Here is 2nd correct version */
float sum_element_v2(float arr[], int length) // let length be a integer encoded by two's-complement
{
int i;
float result;
for (i=0; i<=length-1; i++) {
result += a[i];
};
return result;
}
/* Here is 3rd correct version */
float sum_element_v3(float arr[], unsigned length)
{
int i; // "unsigned i;" is a better declaration for logical operators because of the unsigend argument length.
float result;
for (i=0; i<length; i++) {
result += a[i];
};
return result;
}
// Any correct one?
// Welcome to submit and hava a discussion - !
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment