Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why C has so many different types? [closed]

I write a simple timer function to calculate the time elapsed between start and end

double mytimer(struct timeval *start, struct timeval *end)
{
    return (end->tv_sec - start->tv_sec) + (end->tv_usec - start->tv_usec)*1e-6;
}  

gcc gives the following warnings:

warning: conversion to ‘double’ from ‘__suseconds_t’ may alter its value
warning: conversion to ‘double’ from ‘__time_t’ may alter its value

Here is the definition of timeval:

struct timeval {
    time_t      tv_sec;     /* seconds */
    suseconds_t tv_usec;    /* microseconds */
};

So my question is why does C define so many incompatible types instead of simply using primitive types such as int short ...? It's not user-friendly at all.
And how can I do arithmetic operations on these types?

update

Most of you seemed to have neglected my second question. What is the standard way to add two different types such as time_t and suseconds_t?

like image 377
duleshi Avatar asked Jul 01 '15 09:07

duleshi


1 Answers

Because what time_t etc contains are implementation-defined, there is nothing saying that they should contain a number of seconds as an integer, like the comment in your code implies. The reason is that they want these types to be portable between different systems.

In practice, time.h is indeed rather cumbersome, so most of the time programs end up calling system-specific functions instead.

like image 137
Lundin Avatar answered Oct 04 '22 23:10

Lundin