为什么C有这么多不同类型的? [英] Why C has so many different types?

查看:132
本文介绍了为什么C有这么多不同类型的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个简单的定时器功能来计算 之间的时间开始和结束

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给出了如下警告:

gcc gives the following warnings:

警告:转换从'__suseconds_t'双师型可能会改变其值结果
  警告:转换从'__time_t'双师型可能会改变其值

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

下面是timeval中的定义:

Here is the definition of timeval:

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

所以我的问题是为什么C定义这么多的不兼容的类型,而不是简单地使用原始类型,如 INT 总之 ...?这不是用户友好的。结果
我怎么可以做这种类型的算术运算?

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?

大多数时候,你似乎已经忽略了我的第二个问题。什么是添加两种不同类型的标准方法,如 time_t的 suseconds_t

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?

推荐答案

由于什么 time_t的等包含的实现定义的,有什么说他们应该包含一个数字秒为一个整数,比如在code中的评论暗示。其原因是,他们希望这些类型是不同的系统之间进行移植。

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.

在实践中, time.h中的确是相当麻烦的,所以大部分时间节目的最终调用系统特定的函数。

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

这篇关于为什么C有这么多不同类型的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆