为什么返回值在 c 中环绕 256 [英] Why does return value wrap around 256 in c

查看:54
本文介绍了为什么返回值在 c 中环绕 256的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
程序返回的有效范围是多少Linux/bash 中的值?

这是一个简单的c程序:

Here is a simple c program:

#include <stdio.h>
int main(){
    int a=0, b=100;
    while(a<=b){
        printf("%d\n",a);
        a+=10;
    }
   return a;
}

在 linux 上检查返回值给出 110,这是预期的,因为程序中计算的最后一个表达式是将 110 赋值给 a;但是当我用大于 256 的值替换 b=100 时说 b=260;返回值是 14 而不是预期的 270.当main应该返回范围远大于256的整数时,为什么返回值会绕256?

Checking the return value on linux gives 110 which is expected as the last expression evaluated in the program is assignment of 110 to a; But when I replace b=100 with something greater than 256 say b=260; the return value is 14 and not 270 which was expected. Why does returned value wrap around 256 when main is supposed to return integer whose range is far more than 256?

推荐答案

不幸的是,在基于 Unix 的系统中就是这种情况.即使您将返回类型指定为 int,也不能从 main 返回大于 255 的值.阅读此处.

Unfortunately, its the case in Unix based systems. That you cannot return a value >255 from main even though you specify the return type as int. Read here.

Windows 更宽容,因为它使用 32 位有符号整数作为退出代码

Windows is more permissive in the sense that it uses 32-bit signed integers as exit codes

此外,您不能假设返回值始终是最后一个表达式的值.如果没有明确的 return 语句,则如何推断返回值取决于体系结构.例如,在 ARM 系统上,它在 R0 中的值(有时或 R0+R1)寄存器,在 x86 系统上它是 EAX 寄存器.

Also, you cant assume that the return value shall always be the value of the last expression evaluated. If there is no explicit return statement, how the return value is inferred is architecture dependent. For example, on ARM systems, its the value in R0 ( or R0+R1 sometimes) register and on x86 systems its the EAX register.

这篇关于为什么返回值在 c 中环绕 256的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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