//
you're reading...
Uncategorized

Three Common Runtime Errors In C++

Integer Overflow Error

#include<iostream>
using namespace std;
 
int main(){
  cout << " Example of Integer Overflow" << endl;
  int num = 1;
  unsigned int unum = 1;
  cout << "int num = 1 and when shifted 31 times has value: " << (num << 31) << endl;
  cout << "unsigned int unum =1 and when  shifted 31 times has value: "  << (unum << 31) << endl;
}

Floating Point Roundoff Error

#include<iostream>
using namespace std;
 
int main(){
  cout << endl <<  " Example of Roundoff Error" << endl;
  float f1 = 1000.43;
  float f2 = 1000.0;
  if ((f1-f2) != 0.43) {
    cout << "Warning: Roundoff Error" << endl;
    cout << ".43 != " <<  f1 - f2 << '\n';
  } 
} 
 
/*   Explanation:
1000.43 is represented as the following bitpattern 
-the “s” shows the position of the sign bit, 
-the “e“s show the positions of the exponent bits, 
-the “m“s show the positions of the mantissa bits:
 
    seeeeeeeemmmmmmmmmmmmmmmmmmmmmmm
    01000100011110100001101110000101
 
The shifted mantissa is 1111101000.01101110000101 or 1000 + 7045/16384. 
The fractional part is 0.429992675781. 
*/

Mixed Datatype Error

#include<iostream>
using namespace std;

int main() {
    int i = -5;
    unsigned int j = 6;
    if(i < j)
        cout << i << " is less than " << j ;
    else
        cout << i << " is greater than or equal to " << j;
}
Advertisement

Discussion

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: