Common C Coding Mistakes
C Programming (COP 2220)

Here is a summary of common coding mistakes students have encountered in
writing programs in this class. If you are having problems with your
program, you might find a quick solution here.
-
Use the correct conversion specifier for the declared data type in
a scanf(). A float is %f, an int is %d,
and a double is %lf
(lower
case L). If you
declare a variable to be an int,
don't try to input it with a %f
specifier.
-
Don't use a precision specification in a scanf()
conversion specifier. For example, scanf("%.2f",
&payRate) will not work (at least the ".2" part
won't). Use scanf("%f",
&payRate) instead. Width specifiers can be used,
however.
-
Use the addressing operator (&) for your
variables used as targets for input with scanf()'s,
unless the target is already an address (such as the name of an
array or a pointer variable).
-
The scanf() function can't
be used with the %s
specifier to input a string that contains white space (like
"Electric sander"). Use another
function, like gets().
-
When using getchar()
or scanf() with a %c
(character) conversion specifier, be aware that the last input operation
(like a previous scanf()
or
getchar()) may have
left characters in the keyboard buffer.
-
Do not use the addressing operator
(&) for arguments in a call to printf( ).
- When using puts( ), a newline character ('\n') is automatically
appended, so don't use it for a prompt if you want the user's
input on the same line.
-
There is no semicolon after the
condition:
if (x > 0) /* correct */
...
if (x > 0); /* wrong */
...
-
Use braces ( { } ) around the body of an if
or else branch that
contains multiple statements. You don't need them with a single
statement in the body.
-
If you have a dual-alternative selection to implement, use the if...else
rather than switch
– it's cleaner.
-
There is no condition in the else
branch – only in the if
branch.
-
There is no semicolon after the condition in a
while:
while (x > 0) /* correct */
...
while (x > 0); /* wrong - infinite loop */
...
- The loop index (loop control variable) is not updated inside the
loop
-
You can't compare two strings with
with a relational or equality operator (like >=
or ==). You must use
one of the comparison functions from string.h, like strcmp(
) or strncmp( ), or write your own function.
-
To assign (copy, duplicate) one string
to another, use one of the copy functions from string.h like strcpy(
) or strncpy( ), not the assignment operator (=).
- You can fopen() a file
more than once in a program, but a fclose()
must be executed between fopen()'s.
Review your algorithm to make sure you really need multiple file
open and closes.
|