0

I have this code:

typedef struct{
    double tmp;
} MyTime

void foo(double time){
    printf("A: %f\n", time);
    if(time==0)
       printf("B\n");
}

void main(){
    MyTime mytime;
    foo(mytime.tmp);
}

The output of the program is only "A: 0.000000". Why its not also printing "B"?

I cannot understanded...

thnx

Nick Stavr
  • 13
  • 4
  • Replace `printf("A: %f\n", time);` with the more informative `printf("A: %e\n", time);`. – chux - Reinstate Monica Nov 17 '18 at 03:30
  • Hot tip - uninitialized variables in C aren't necessarily zero. – Carl Norum Nov 17 '18 at 03:32
  • @CarlNorum: This is not a duplicate of [that question](https://stackoverflow.com/questions/17404513/floating-point-equality-and-tolerances). There is no floating-point rounding in this question, and comparing with a tolerance is not an appropriate solution. The actual problem here is the object was not initialized, so the required solution is to initialize it. Please do not mark questions as duplicates promiscuously based on superficial resemblances. – Eric Postpischil Nov 17 '18 at 12:53
  • When you post code in a question, post exactly the code used. Copy and paste it, do not retype. The missing semicolon in the `typedef` means the code you entered in the question could not be the code you actually compiled. – Eric Postpischil Nov 17 '18 at 12:53

1 Answers1

0

The code you show fails to initialize mytime. In C, an object defined inside a function without static is not initialized by default to zero (or any other value). Its value is indeterminate, and using it generally results in undefined behavior.

In this case, the code behaved as if mytime.tmp had a small non-zero value, such as 1e-9. When formatted with %f, small values are formatted as “0.000000”. And, since the value is not zero, time==0 returns false. (Changing %f to %g would likely reveal a small non-zero value.)

Since the code fails to initialize mytime, the value in mytime.tmp could also have been very large, or the program could have crashed.

Also, the code as posted fails to compile and has a number of issues:

  • The typedef definition of MyTime must be terminated with a semicolon.
  • The code should contain #include <stdio.h> to declare print.
  • main should be declared int main(void) or int main(int argc, char *argv[]).
Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312