Re: long veriable causes problem

From: B. v Ingen Schenau (bart_at_ingen.ddns.info)
Date: 04/30/04


Date: Fri, 30 Apr 2004 11:38:38 +0200

Ronen Kfir wrote:

> Hi,
> The following code works only with int veriable defenitions. with long
> I get wrong results, -1 does not terminate program & negative numbers
> give back odd numbers.
>
> please help.
>
>
> TIA
> Ronen
>
>
> //calculates an admin digit based on //
> //program rules.//
>
> #include<stdio.h>
>
> //veriable definition//
> long result(long x);
> long bikoret;
> long number;
>
> void main()

According to the definition of C and C++, main must return an int, so
  int main()
> {
> puts ("\nPlease enter a positive integer");
> scanf ("%d",&number); //first number input//

This is where your error lies.
When scanf processes the %d specifier, it expects to store the result in an
object of type 'int'. You pass it an object of type 'long int' and because
of this mismatch you get the dreaded undefined behaviour.

The correct way to read a value into a long int is
  scanf ("%ld", &number);

>
> while (number!=-1 //exit from loop if number=-1//
> {
> if (number>=0) //if number>0 comete //
> //the following code//
> {
> bikoret=result(number); //send veriavle //
> //number as an argoment //
> //to result() function. //
> //Then asign the return value of result() to
> //
> //bikoret veriable//
> printf ("Administration digit is %d\n", bikoret); //print output of

Here you should also use %ld to get correct results.

> bikoret//
> }
> else
> {
> puts ("\npositive integres only!"); //if number<0//
> //don't calculate admin digit//
> }
> scanf ("%d",&number); //next number input//

Same here.

Bart v Ingen Schenau

-- 
a.c.l.l.c-c++ FAQ: http://www.comeaucomputing.com/learn/faq
c.l.c FAQ: http://www.eskimo.com/~scs/C-faq/top.html
c.l.c++ FAQ: http://www.parashift.com/c++-faq-lite/


Relevant Pages

  • Re: sort array
    ... "Ronen Kfir" wrote in message ... > I have to take array of float and sort it. ... > void sorting(float A, int n); ...
    (alt.comp.lang.learn.c-cpp)
  • Re: split a string
    ... Ronen Kfir wrote: ... but not much buffer checking: ... int main ...
    (alt.comp.lang.learn.c-cpp)
  • Re: wrong print
    ... you must be using non-standard libraries. ... int max_line_len = 1024; char **Amm,**Pss; ... char* readline; void scandir; ... Before posting for the first time to a group ALWAYS read the FAQ ...
    (comp.lang.c)
  • Re: malloc for members of a structure and a segmentation fault
    ... almost the entire FAQ, but can't seem to figure out this problem. ... and a pointer to a character pointer */ ... int main { ... void test; ...
    (comp.lang.c)
  • Re: [C] structures
    ... > struct student { ... > int main ... char grade; ... a.c.l.l.c-c++ FAQ mirror: http://nullptr.merseine.nu:8080/acllcc++.html ...
    (alt.comp.lang.learn.c-cpp)