|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
1200+ fellow developers rate and compare features of the top IDEs, like Visual Studio, Eclipse, RAD, Delphi and others, across 13 categories. Enjoy this FREE Download of the IDE User Satisfaction Study by Evans Data Corporation. Download Now!
|
|
#1
|
|||
|
|||
|
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
|
|||
|
|||
|
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. |
|
#3
|
||||
|
||||
|
>> #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! |
|
#4
|
|||
|
|||
|
Thank-You
Thank-you,
The problem has been solved! |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > C Programming > Return Value |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|