Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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;
}
Posted
Updated 4-Mar-17 5:23am

Because the compiler is perfectly happy to implicitly cast the char value to an int and return it.
 
Share this answer
 
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; .
 
Share this answer
 
Have also a look at this page: Implicit conversions - cppreference.com[^].
 
Share this answer
 
Quote:
infact when i am using char in place of int it is showing error.

Because of your compiler oddities.
A C compiler should not even compile your code.
C++
#include<stdio.h>
// Here is missing the func prototype,
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));
// here is missing a return
    }
    else 
    return c;
}

Quote:
why it is not showing error as return value is not of type int.

Because of compiler internals, it can handle some things and not some others.
No one can predict what will be ok or not without empirical experiment.
 
Share this answer
 
Comments
Richard MacCutchan 4-Mar-17 11:42am    
The code compiles fine, with a couple of warnings.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900