0

Suppose you want to add some huge numbers

int add(int &a, int b){
    return a = a+b;
}
int add_(int a, int b){
    int c = a+b;
    return c;
}

This is what I have in my mind. I was actually thinking about adding two vectors then I generalized it to numbers. If you want to use the add style, what will you do if you need the original value of a? And if you want to use the add_ style, isn't it memory waste if you have to add, subtract and multiply a lot of large numbers?

What is the standard way of doing this?

merovingian
  • 515
  • 2
  • 9
  • I am afraid there's no _"standard way"_ to do that. – πάντα ῥεῖ Oct 16 '22 at 13:33
  • At least a common approach? @πάνταῥεῖ – merovingian Oct 16 '22 at 13:34
  • There are libraries specialized for that. – πάντα ῥεῖ Oct 16 '22 at 13:36
  • What do you mean by "need the original value of `a`"? Before you call a function, you already have that value. If you want to destroy it inside `add`, make a copy before you call that function. Take a look at LAPACK interface, for example. – Evg Oct 16 '22 at 13:37
  • After passing it by reference add(a, 1), and you will have new a value which is a+1. And if you want to pass 'a' again after calling add function, for example: add(a, 1) you will be passing a+1 rather than original 'a' itself @Evg – merovingian Oct 16 '22 at 13:40
  • 1
    Your first try with the reference is clearly wrong, you don't want to change your inputs and reference allow implementation to change a. So I would write it as `vector add(const vector& v1, const vector& v2) { return { v1.x + v2.x, v1.y + v2.y}; }` The `const`'s are there to say you're not going to change v1 and v2, and the references are there to avoid unecessary copy of v1 and v2 – Pepijn Kramer Oct 16 '22 at 13:41
  • 1
    `add(a, b)` that modifies either `a` or `b` is semantically broken. It doesn't model addition and should be called by some other name. – Evg Oct 16 '22 at 13:42
  • 1
    What do you mean by adding "vectors and numbers"? What are "huge numbers"? Are you asking about [big integers](https://stackoverflow.com/questions/4507121/c-big-integer) implementation? – Bob__ Oct 16 '22 at 13:43
  • Can you explain? I don't know about the terminology but it returns a + b anyway @Evg – merovingian Oct 16 '22 at 13:45
  • 1
    Suppose you have two `int`s `a` and `b`. Will `a + b` modify them? No. Follow the same rule for your data types. An operation that modifies `a` is `a += b`. You can replace `+=` with a plain function, but it should not have a name `add` - your code should be readable and understandable by people. For the same reason you won't use a name `mul` or `div` for `a + b`, although technically you could. – Evg Oct 16 '22 at 13:49
  • 1
    Use two separate functions named `operator +` and `operator +=`. – n. m. could be an AI Oct 16 '22 at 15:12

0 Answers0