I often see short, "clever" hacks be glorified ubiquitously, but only by dilettantes owning dummy introductions to programming and computer science. Nevertheless, ask any seasoned expert and they will agree that hacking is the naïve programmer's only means of assuaging their grievous wail for acknowledgement (or anything at all).
1 2 3 4
|
int f(int a[], int n)
{
return n == 1 ? a[0] : (n--, f(a + (a[0] > a[n]), n));
}
|
"My solution is four lines long" is the popular mantra of these subjects, followed by blind wrangles as to the "intricate" workings of their creations. But let us be frank for a moment: I bet you have no clue what the above function does; it is very confusing! But this is typical of hacks.
Moreover, you decide to grab this snippet and translate it to a syntactically simpler language (after doing your homework on the evident C++ constructs), like Python:
1 2 3 4 5 6
|
def f(a, n):
if n == 1:
return a[0]
else:
n -= 1
return f(a + (a[0] > a[n]), n)
|
You quickly discover that it returns something for arrays of size 1 but crashes for anything larger. Clearly, this hack is too localized; it depends on both the pointer arithmetic and the representation and evaluation of the Boolean type characteristic of C and C++. In fact, if the compiler writers decide to fiddle with the language, our beloved hack could be at stake, as it is language-dependent.
Finally, in your confusion, you ask an educated software engineer to decipher what the hacker is trying to do, and he comes up with this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
int minimum(int array[], int size)
{
int minimum_element = array[0];
for (int i = 1; i < size; i++)
{
if (array[i] < minimum_element)
{
minimum_element = array[i];
}
}
return minimum_element;
}
|
This is self-explanatory and astronomically more maintainable; what would our petty hacker do if he had to modify his treasure to find the minimum element in the even indexes of the array? The engineer would only need to change line
5 in his code to
for (int i = 2; i < size; i += 2)
. Hacks are unmaintainable.
Overall, if you write code for yourself alone, do as you please, but if you intend to share it with others, please stress on good, healthy software engineering practices and spare others from your conceptual verbosity.