Sudhanva Narayana Sudhanva Narayana - 4 years ago 83
C++ Question

C++: Similar mod operations printing different values

I am trying to perform some custom operation but I noticed the following error.
While calculating the value of

t
, I get desired output but for
s
I am getting negative values for no reason.

#include <bits/stdc++.h>

using namespace std;

int main()
{
char s = 'r';
char temp1 = s;

char t = 'a';
char temp2 = t;

s = (int(temp1) % int(96)) + (int(s) % int(96)) + 96;
cout << int(s) << " ";

t = (int(temp2) % int(96)) + (int(t) % int(96)) + 96;
cout << int(t) << endl;
}



I have to use this logic elsewhere in a bigger program, I am getting the same error in both the cases

Output
-124
98


I don't understand why -124 is begin printed


Answer Source

You are hitting an overflow issue with an 8-bit integer type (char).

This expression is

s = (int(temp1) % int(96)) + (int(s) % int(96)) + 96;

Algebraically, your code simplifies to this:

s = 114 % 96 + 114 % 96 + 96;

s = 18 + 18 + 96;

s = (signed char)132;  // overflow!  132 won't fit in range [-128..127]

s = -124;

Change the declaration of s and t to be of type int. And some helpful ways to improve your code style are made as well:

int main()
{
    int s = 'r';
    int temp1 = s;

    int t = 'a';
    int temp2 = t;

    s = temp1 % 96 + s % 96 + 96;
    cout << s << " ";

    t = temp2 % 96 + t % 96 + 96;
    cout << t << endl;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download