Quantcast
Channel: User Lundin - Code Review Stack Exchange
Viewing all articles
Browse latest Browse all 42

Answer by Lundin for My first C program: quadratic formula calculator code

$
0
0

Overall clear and readable. Some remarks:

  • atoi is one of those standard library functions that should never be used. It is 100% equivalent to strtol family of functions, except that the latter have error handling and support for other number bases than decimal.

    Since you are using this function on user input which has not been sanitized, you should not use atoi, because it invokes undefined behavior when the input is incorrect.

  • The error handling in case fgets fails should be better - you shouldn't continue execution. Similarly, when you swap out atoi for strtol, you will be able to do some more error handling as well. For simple beginner-level programs you probably just want to print an error and then exit.

  • There is no obvious reason why buffer should be allocated in the caller, since it is only used internally by the function. It would have been better off as a local variable inside the function.

  • In case you are aiming for floating point arithmetic, make it a habit to convert all operands in the expression to float. That eliminates the chance of accidental type-related bugs.

    x1 = (float)-b / (2.0f * (float)a);

    That is, unless the intention is do to part of the calculation in fixed point arithmetic. In such rare cases, split the expression in several lines.

  • deltaSqrt = sqrt(delta); converts everything to fixed point integers. Is that really the intention here? Because the results will be very different compared to floating point.

  • Minor issue - using \ to split strings is fishy practice - it is more readable to just to let the pre-processor do automatic string literal concatenation:

    printf("Quadratic Formula Calculator\n\n""Given a function in normal form:\n"

    This is 100% equivalent to "Quadratic Formula Calculator\n\nGiven a function in normal form:\n"

  • Minor - You are using inconsistent brace placements here: int main(void) {. This is likely caused by an IDE configured to use a certain style or give a default main() - if so, you might want to look up how to set the IDE to cooperate with you instead of working against you. It's a major waste of time to have a code editor spit out code formatting which doesn't correspond with your preferred style.


Viewing all articles
Browse latest Browse all 42

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>