i have a doubt in my code it goes to infinite loop.

Hi,

Following is my code which i wrote and got infinite loop.
#include<stdio.h>
#include<conio.h>



int count(int i)
{
   return i++;   // this is a problem but if I change it to i=i+1 it works I want  to   
                       //know why it happens?

}


int main(void)
{
       clrscr();  // this is to clear screen from previously run programs

       for(int i=0 ; i<10 ; i = count(i) )    // I am trying to increment counter by
                                                           //calling         function.
       {
      printf(" count is %d",i);

       }
       getch();  // this is to pause screen in turbo c++
       return 0;
}


Thanks.

Comments

  • Read up on the difference between i++ and ++i

    https://www.cs50.net/resources/cppreference.com/operator_precedence.html

    The problem is with [icode]return i++;[/icode]
  • "return i++" will return the value of i, and plus i by1.
    "return ++i" is right.
  • Why would you want to write a function for an operator? We already know what for loops do so the function should at least be called increment.
  • Why would you want to write a function for an operator? We already know what for loops do so the function should at least be called increment.

    This is a learning exercise for using functions, including the return value.

    Since the return value is never used in main(), it doesn't do anything, however.

    In C, forum parameters (like i), are passed ONLY by copying. If you want to change the "i" variable in main(), you need to pass either:

    1) The address of i, into counter(): counter(&i), void counter(int *i), would be the call and function definition. This would change the value of i, in main(), since the copy of the address of i, is the same as the original address of i. i.e. the address 221B Baker St. is the same home of Sherlock Holmes, as the copy of the address, 221B Baker St.

    or

    2) Have the value of i returned and *immediately* caught by a variable in main():

    return ++i;

    And in main():

    i=counter(i); //the copy of i in counter, returns it's value to the i in main().

    or

    return ++i;

    printf("%d",counter(i)); //printf() immediately uses the returned value of i.


    Welcome to the forum, nitsaina! ;)
Sign In or Register to comment.