0

I have the following code:

#include <stdio.h>
#include <time.h>

clock_t a;

void f(void) {
    a = clock();
    printf("in f(): %g\n", a);
}

void main(void) {
    f();
    printf("in main(): %g\n", a);
}

Compiling it with MinGW gcc and running it produces output similar to this:

in f(): -1.#QNAN
in main(): 1.49845e-307

Question: Why does a contain -1.#QNAN? While I understand what it means, I do not see what went wrong in the code. At first, I speculated that it has something to do with the printing format specifier for type clock_t, but answers from this stackoverflow thread says otherwise. Even to make sure, I did a quick digging in the standard headers and found out that clock_t is a typedef for long (at least on my machine), which means that there is nothing wrong with regards to displaying the value. Could it be a bug in the clock() function?


Edit: Just after reading the comments, I realized that my actual problem is that I was expecting a to be some super small floating-point value so badly that I forgot clock_t is, as I said, defined on my machine as of type long. Sorry for the bother and thank you all for your time.

Christian
  • 553
  • 4
  • 16
  • 4
    The answer to the other question uses `%g` after converting the value to `double`. You don't seem to do that. – Bo Persson Feb 13 '18 at 15:30
  • 2
    The type of `clock_t` is unspecified. Therefore `%g` might not be the appropriate format operator: http://en.cppreference.com/w/cpp/chrono/c/clock_t – Richard Critten Feb 13 '18 at 15:32
  • `clock_t` is an integer type, not a `float`, so you cannot use `%g` format to print it, check `printf(3)` documentation for valid format specifiers. – Luis Colorado Feb 14 '18 at 19:58

2 Answers2

2

Please always take a look at your compiler warning:

warning: format specifies type 'double' but the argument has type
      'clock_t' (aka 'unsigned long') [-Wformat]
    printf("in f(): %g\n", a);
                    ~~     ^
                    %lu

Compiler even tells you how to fix. In short, you can't specify a double to printf() when the data is unsigned long.

llllllllll
  • 16,169
  • 4
  • 31
  • 54
  • Sorry, that message is CLANG specific, he can be using a compiler that doesn't give such a warning. Would be better to recommend him to look at `printf(3)` documentation about how to print integer types, like `clock_t`. – Luis Colorado Feb 14 '18 at 19:59
2

%g is for printing floating point numbers, but you passed a clock_t (which can be any arithmetic type; such as a 32 bit integer).

You need to cast to a double if you want to use %g:

printf("in main(): %g\n", static_cast<double>(a));
Simple
  • 13,992
  • 2
  • 47
  • 47