-1

It seems that (type-name) returns the default value for the type.

Consider the following code:

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

int main() {
  printf("value: %ld\n", ((time_t) -1));
  printf("value: %d\n", ((int) -1));
}

Use gcc code.c to compile it. Running ./.aout produces:

value: -1
value: -1

I am using GCC 8.1.0 on Ubuntu 16.04.5 LTS.

And TIME(2) man page has the following text:

On error, ((time_t) -1) is returned, and errno is set appropriately.

I browsed the C11 language specification N1570. But I can't find a description about the above usage.

9
  • 7
    I'm sorry to be a little harsh, but if you don't know about casting then you need to either read your books more thoroughly, or stop skipping classes. Jan 22, 2019 at 12:44
  • It's in section 6.5.4
    – user2201041
    Jan 22, 2019 at 12:45
  • You never use the time() function. How can you have its return value? (time_t) is a cast. Jan 22, 2019 at 12:46
  • 2
    I'm voting to close this question as off-topic because it is basic C knowledge, and it is not a programming question Jan 22, 2019 at 12:47
  • 4
    @P__J__: Neither of those are the criteria for what may be asked. (Being a programming problem is one qualifying reason—in a list of several reasons.) Jan 22, 2019 at 12:56

1 Answer 1

2

It seems that (type-name) returns the default value for the type.

What's that even supposed to mean? There exists no default values for types in C. Your two printf lines does this:

  • printf("value: %ld\n", ((time_t) -1));

    Here -1 has type int. You force a conversion from int to time_t, the latter having an unspecified format, other than being "a real type capable of representing times".

    Then you lie to the program and say that the value passed is of type long int. You invoke undefined behavior, anything can happen. In your particular case, it seems to give the original value -1. It could as well print garbage or cause a program crash.

    This has absolutely nothing to do with the time() function, which isn't present anywhere in the code.

  • printf("value: %d\n", ((int) -1));

    -1 has type int. You tell the compiler to convert from int to int. The compiler, being polite, doesn't question why you'd write such meaningless code, but likely just pre-process it back into -1.

    You then tell printf that you want to print your int with value -1 as an int. And then it does that.


I browsed the C11 language specification N1570. But I can't find a description about the above usage

See C11 6.5.4 Cast operators and C11 7.21.6.1 The fprintf function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.