如何在C +操作员的工作量? [英] How does the + operator work in C?

查看:134
本文介绍了如何在C +操作员的工作量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在了解如何原始运算符,如 + - * / 用C实现的,我发现从下面的代码片段一个有趣的答案

When understanding how primitive operators such as +, -, * and / are implemented in C, I found the following snippet from an interesting answer.

// replaces the + operator
int add(int x, int y) {
    while(x) {
        int t = (x & y) <<1;
        y ^= x;
        x = t;
    }
    return y;
}

似乎这个函数演示如何 + 实际工作的背景。然而,这是太混乱了,我去了解它。我认为,这样的操作是使用编译器很长一段时间生成的程序集的指令完成了!

Seems that this function demonstrates how + actually works in the background. However, it's too confusing for me to understand it. I believed that such operations are done using assembly directives generated by the compiler for a long time!

我的问题是:在 + 运营商实现为code贴在的实施?这是否采取补或其他实现相关的功能优势?我会AP preciate非常多,如果有人可以解释它是如何工作的。

My question is: Is the + operator implemented as the code posted on MOST implementations? Does this take advantage of two's complement or other implementation-dependent features? And I'll appreciate it very much if someone can explain how it works.

嗯......也许这个问题是关于所以有点偏离主题,但我想这是有点好通过这些运营商关注一下。

Hmm...Maybe this question is a bit off-topic on SO, but I suppose it's somewhat good to look through these operators.

推荐答案

要学究,将C规范没有指定的如何的另外实施。

To be pedantic, the C specification does not specify how addition is implemented.

但要实事求是,对整型小于或等于CPU的字长的 + 运营商处获得直接转化为CPU的加法指令,并且较大的整数类型会转换成多个指令。另外一些额外的位来处理溢出。

But to be realistic, the + operator on integer types smaller than or equal to the word size of your CPU get translated directly into an addition instruction for the CPU, and larger integer types get translated into multiple addition instructions with some extra bits to handle overflow.

在CPU内部使用逻辑电路来实现另外,并且不使用循环,bitshifts,或任何具有紧密的相似性为C如何工作的。

The CPU internally uses logic circuits to implement the addition, and does not use loops, bitshifts, or anything that has a close resemblance to how C works.

这篇关于如何在C +操作员的工作量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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