1

I'm a little confused about which is better or correct to declare a function in "for" & "member function" in a class. I think the best way is trying not to make these cases...

Here are some examples.

template<typename K> class Bigger {
public:
    bool operator()(const K& a, const K& b) const {
    int aa = a.getValueJ() * a.getValueK();
    int bb = b.getValueJ() * b.getValueK();

    return aa > bb;
    }
};

template<typename K> class Bigger {
public:
    bool operator()(const K& a, const K& b) const {
      return (a.getValueJ() * a.getValueK()) > (b.getValueJ() * b.getValueK());
    }
};

=======================================

for (auto i : time1) {
  int t = t.getValueJ() / t.getValueK();
      cout << t << " ";
}

for (auto i : time1) {
     cout << t.getValueJ() / t.getValueK() << " ";
}

It seems like a very novice question.

Could you give me a little advice for them?

Have a nice day~

  • I'm not sure if I understand your question correctly. Better in what regard? The only difference I see is using a temporary variable or not, which is a question of personal preference (or company guidelines, etc.) and mainly opinion based. – Lukas-T Nov 21 '20 at 14:20
  • In this case, it doesn't matter, since you're only reading the value of each field once. If you were accessing the same field's value multiple times, then it *might* be ***slightly*** faster if you cached it in a local variable. But still, it really doesn't matter. Make the decision based more on readability. Capturing the value in a local variable might prevent extremely long lines in your code. – Cody Gray - on strike Nov 21 '20 at 14:21
  • You're asking about having one longer statement or several shorter statements using intermediate variables? Opinion questions are off-topic on SO, but see: https://softwareengineering.stackexchange.com/questions/203684/is-fewer-lines-of-code-always-better and https://softwareengineering.stackexchange.com/questions/339495/at-what-point-is-brevity-no-longer-a-virtue – aschepler Nov 21 '20 at 14:22
  • Oh, That means I have to care about readability. Thank you everybody :) – Hyeongseok Yang Nov 21 '20 at 14:39
  • You *always* have to care about readability. :-) – Cody Gray - on strike Nov 21 '20 at 14:41

0 Answers0