Thread: Return Value

    #1
  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2003
    Posts
    24
    Rep Power
    0

    Return Value


    Hello!

    I have question regarding the return value of a function. I have two separate C files

    In file1 I have:
    double value = getValue();
    printf("Value: %f\n", value);

    In file2 I have a global defined as:
    double v = 2;

    Also in file2 I have a function defined as:
    double getValue() {
      printf("V: %f\n", v);
       return v;
    }

    When this function gets called from file 1, it prints out the value correctly in getValue(), however, when I print out the return value, I get an incorrect value.

    How can this be happening?

    Thank-you
  2. #2
  3. No Profile Picture
    .
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2002
    Posts
    296
    Rep Power
    12
    these two pieces of code in seperate files:
    Code:
    /* file 1 */
    #include <stdio.h>
    #include "file2.c"
    
    main()
    {
    	double value = getValue(); 
    	printf("Value: %f\n", value);
    }
    Code:
    /* file 2 */
    #include <stdio.h>
    
    double v = 2; 
    
    double getValue()
    { 
    	printf("V: %f\n", v); 
    	return v;
    }
    result in:
    Code:
    V: 2.000000
    Value: 2.000000
    which is what you were expecting, i think.

    could the problem be something to do with the include file 2 part? by the way, when i compiled these 2 files i only needed to specify file1.c in the compilation command, as file2.c is linked to and included within file1. h.t.h. if it doesn't help, you need to post what your actual wrong results were and a description the file setup i think.
  4. #3
  5. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,625
    Rep Power
    4247
    >> #include "file2.c"
    This is valid, but bad programming practice. We've had quite a few threads about this topic here. Best way to handle it is to make a file2.h file to contain the prototype of the function in file2.c:
    Code:
    /* file2. h*/
    double getValue();
    
    /* file2.c */
    #include <stdio.h>
    #include "file2.h"
    double v = 2; 
    
    double getValue()
    { 
    	printf("V: %f\n", v); 
    	return v;
    }
    
    /* file1.c */
    #include <stdio.h>
    #include "file2.h"
    
    int main(void)
    {
    	double value = getValue(); 
    	printf("Value: %f\n", value);
    	return 0;
    }
    Hope this helps!
  6. #4
  7. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2003
    Posts
    24
    Rep Power
    0

    Thank-You


    Thank-you,

    The problem has been solved!

IMN logo majestic logo threadwatch logo seochat tools logo