[Solved]: Is badly written code derogatory to the compiler?

Problem Detail: I was having a heated debate with a friend of mine (who considers me an idiot, mind you) and we were arguing about whether a compiler has an index, or coefficient, that judges how poorly code is written. Things such as useless for loops, declared variables that aren’t used, excessively verbose parameter names, and the likes. He told me that there is no such “stupid” thing. I got mad and told him that the index exists and that smart people writing compilers wanted to make the compiler have “feelings” where it would analyze the code, generate the coefficient using an algorithm, and change how well it compiles the code based of how poorly the person wrote the code. I guess, to alleviate any confusion, what I’m asking is, do compilers have feelings? Err, well not literally, figuratively, by using an algorithm and code quality coefficient. All answers are greatly appreciated! Thank you!

Asked By : Rogue Shakuras

Answered By : jmite

So, something similar to what you’re describing exists, but not the way exactly. A compiler can’t generally identify “bad” code. In particular, it cannot usually fix incorrect code. If you make a mistake, not only is it undecidable for the compiler to tell if you made a mistake, but there’s no specification of your program for the compiler to compare to, determining if it is a mistake. There are some general exceptions to this, the most notable one being typechecking. But there, the compiler isn’t keeping any sort of coefficient, it just rejects poorly-typed code, or emits a warning. For improve code, there is a part of the compiler called an optimizer. It will look for easy tricks that will speed up your code. Some of its tools include:

  • Reordering instructions to improve speed
  • Replacing a function with its definition, to reduce the overhead of calling a function (inlining)
  • Evaluating expressions only involving constants
  • Removing run-time safety checks when it knows they’re not needed
  • Storing sub-expressions that are used more than once

However, this is not at all focused on “bad” code. It is more focused on finding ways to generate fast machine code in a way that is simply not practical to do by hand. Writing code using functions is certainly not bad, but the compiler is able to make it faster in a way that a good programmer would never write. The compiler can’t do magic. If you use a slow algorithm, like BubbleSort instead of QuickSort, the compiler can’t fix that for you. There are some measures of code quality, but these are generally not included in a compiler. Rather, they are part of separate code-auditing tools.

Best Answer from StackOverflow

Question Source : http://cs.stackexchange.com/questions/44368

Leave a Reply