This is a two part question.
-
I have a small code that adds numbers; however the numbers often grow faster than
long longcan hold.So I thought I’d make a class to move it over.
My thought process is given 3
long long a, b, c;,Add everything to
cand whencis at capacity, add one toband setcto zeros; oncebis “full” add one toaand setbandcto zero and so on.So, I have to check to see if
cis at capacity before I reset it and add one toband so on!Is there a way to check for that?
-
Can someone point me to the right direction to make my own data type. Visually, I put 3
long longs together like the above and the data type would do what I talk about above.
Finally, I would like to treat my new data type just like i do to ints:
int a = 0;
I would like to be able to do
mydatatype a = 0;
English is not my first language.
Testing if an integer is at capacity means that your code will be very inefficient. For example, to add 123 you’d need to do 123 increments and 123 comparisons.
A better way would be to determine if the operation will overflow before performing the operation. For example (for unsigned integers only):
This works because
ULLONG_MAX - acan not overflow. When you start looking at signed integers it becomes a larger problem becauseLLONG_MAX - acan overflow (ifais negative), andLLONG_MIN - acan also overflow (ifais positive). You need to test both ways:Once you’ve determined if it would have overflowed you need to handle that case. For example; if you’re using multiple integers to represent one larger integer; then (for unsigned integers):
Please note that you have to be very careful to avoid accidental overflows in temporary calculations involved in handling the original (avoided) overflow.
If you use multiple signed integers to represent one larger signed integer, then the logic behind overflow handling becomes complex and error-prone. It is theoretically possible; however it’s far better to separate the signs of the numbers and then do operation (or its inverse – e.g. subtracting a positive number instead of adding a negative number) on unsigned integers alone; especially if you need to use 3 or more integers to represent one huge integer, or if you need more complex operations like multiplication and division.
Of course once you start down this path you’re effectively implementing your own “big number” code, and should probably find/use a suitable library instead.
Finally, if you’d like to treat your new data type like primitive data types (e.g. and be able to do things like
mydatatype a = 0;) then you’re out of luck – C doesn’t work this way. Essentially, C is beautiful because it doesn’t allow complex things to be hidden from people trying to read/understand the code; and you’d have to use a less beautiful language like C++ if you want to hide important information from unsuspecting victims. 😉