使用int时为什么没有错误 [英] Why there is no error when int used

查看:80
本文介绍了使用int时为什么没有错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了int fun(intx),但为什么它没有显示错误,因为返回值不是int.infact类型,当我使用char代替int时它显示错误。



我的尝试:



i have used int fun(intx) but why it is not showing error as return value is not of type int.infact when i am using char in place of int it is showing error.

What I have tried:

#include<stdio.h>
int main()
{
    int n,i;
    printf("enter n\n");
    scanf("%d",&n);
    fun(n);
}
int fun(int x)
{int i;
char c='*';
    if(x>=1)
    {for(i=1;i<=x;i++)
    printf("%c",fun(x-1));}
    else 
    return c;
}

推荐答案

因为编译器非常乐意将char值隐式转换为int并返回它。
Because the compiler is perfectly happy to implicitly cast the char value to an int and return it.


另请注意,如果 x> = 1 ,那么在完成循环后,您将失去函数 fun ,但是你没有return语句。因此,无论在特定机器寄存器中发生什么值,都将由调用者接收,并作为字符打印。您需要在返回c; 之前删除 else 语句。
Note also that if x >= 1 then after completing the loop you fall out of the function fun, but you do not have a return statement. So whatever value happens to be in a particular machine register at that point will be received by the caller, and printed as a character. You need to remove the else statement before return c; .


有另请看这个页面:隐式转换 - cppreference.com [ ^ ]。
Have also a look at this page: Implicit conversions - cppreference.com[^].


这篇关于使用int时为什么没有错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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