这是在C中实现+运算符的方式吗? [英] Is this how the + operator is implemented in C?

查看:93
本文介绍了这是在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;
}

该函数似乎演示了+在后台的实际工作方式.但是,这让我难以理解.我相信这样的操作是使用编译器长时间生成的汇编指令来完成的!

It 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!

+运算符是否作为 MOST 实现中发布的代码实现?这会利用二进制补码或其他与实现相关的功能吗?

Is the + operator implemented as the code posted on MOST implementations? Does this take advantage of two's complement or other implementation-dependent features?

推荐答案

要学究,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在内部使用逻辑电路来实现加法运算,并且不使用循环,移位或与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天全站免登陆