-1

This is not related to classes. I have a function that returns a constant based on the input. A minimum working example related to my question is added below.

#include <iostream>

namespace surfaceArea
{
constexpr int triangle = 11;
constexpr int square = 25;
}

int getSurfaceArea(bool isTriangle)
{
    return isTriangle? surfaceArea::triangle : surfaceArea::square;
}

int main ()
{
  const int numSides = 3;
  const bool isTriangle = (numSides == 3);
  const int surface = getSurfaceArea(isTriangle);
  std::cout << "Surface Area is " << surface;
  
  return 0;
}

Should I use static or const for the function getSurfaceArea(bool isTriangle). That is as const int getSurfaceArea(bool isTriangle) or static int getSurfaceArea(bool isTriangle)? What are the differences between these two keywords and What is the best practice to use in a similar scenario?

Fareanor
  • 5,900
  • 2
  • 11
  • 37
  • 2
    `const int` on the return type doesn't matter. You're returning by value. – Jason Oct 05 '22 at 09:08
  • Also, *"best practices to format the above code"* seems opinion based. – Jason Oct 05 '22 at 09:09
  • 2
    What about using a [good C++ book of your choice](https://stackoverflow.com/a/388282/11455384) to properly learn C++ ? Because `static`and `const` are not the same thing at all. SO is not meant to replace your teaching courses. – Fareanor Oct 05 '22 at 09:11
  • 1
    Also `static int getSurfaceArea(bool isTriangle)` will make the function have *internal linkage*. So, `const` and `static` **have completely different roles**. You can't compare them. That is, you shouldn't pick random keywords and start comparing them. The roles of these keyword are explained in any [good c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Jason Oct 05 '22 at 09:12
  • For above function I might use `constexpr`. – Jarod42 Oct 05 '22 at 09:22

1 Answers1

1

Returning a const T where T is copyable and not a ref-type is almost never advised: your caller can simply assign it to another T and change the value. It brings no benefits.

When your global (non-member) function is static, it means it has implicit linkage. That is, it can only be called from the current C++ file. If you only have one C++ file, it doesn't matter; even if you have multiple, you might consider putting it to an anonymous namespace instead, if that's what you want. If you have no such intentions to keep it local to the current C++ file, then it shouldn't be static.

lorro
  • 10,687
  • 23
  • 36