Logic error

From Wikipedia, the free encyclopedia

In computer programming, a logic error is a bug in a program that causes it to operate incorrectly, but not to fail. Because a logic error will not cause the program to stop working, it can produce incorrect data that may not be immediately recognizable.

With a logic error, the program can be compiled or interpreted (supposing there are no other errors), but produces the wrong answer when executed.

Contents

[edit] Common causes

The mistake could be the logical error in a statement (for example, a wrong or incorrect formula), an error in an algorithm, or even the wrong algorithm selected.

[edit] Debugging logic errors

One of the ways to find these type of errors is to output the program's variables to a file or on the screen in order to define the error's location in code. Although this will not work in all cases, for example when calling the wrong subroutine, it is the easiest way to find the problem if the program uses the incorrect results of a bad mathematical calculation.

[edit] Examples

This example in C contains a logic error. After 'scanf', 'money_in_store' is checked instead of 'money'.

#include <stdio.h>

int money, money_in_store;

main()
   {
   do
      {
      printf("Enter amount of money (0 to exit): ");
      scanf("%d", &money);
      if (money_in_store == 0)   // Should be 'if (money == 0)'
         {
         printf("%d money on exit\n", money_in_store);
         exit(0);
         }
      money_in_store += money;
      } while(1);
   return(0);
   }

[edit] See also

In other languages