0

i am confused with code below.

#include <stdio.h>
#include <stdlib.h>

int event(char a[],char x,char n);
int main(int argc, char *argv[]) {
    int n,y;
    char a[40],x;
    printf("enter a string\n");
    gets (a);
    printf("enter the character\n");
    x=getche();
    printf("\nenter the event\n");
    scanf("%d",&n);
    y=event(a,x,n);
    if(y==0)
    printf("%dth event not found\n",n);
    else
    printf("%dth event is in position:%d",n,y);
    getch();
    return 0;
}
//*******************************************************
int event(char a[],char x,char n){
    int i,cnt=0;
    for(i=0;a[i];i++){
        if(a[i]==x)
        cnt++;
        if(cnt==n)
        return(i+1);
    }
    return 0;
}

in function event a[],x,n are showed as character, and function is as int,but in main function n and y are int,and when we call event we sent them as int. n,y are different when we call event.why?is code correct?

1
  • Code is syntactically correct. Problem you are facing is because compiler will do some promotions.Try reading c_type casting integral promotions
    – kernel
    Jan 10, 2014 at 8:53

3 Answers 3

3

A prvalue of an integer type or of an unscoped enumeration type can be converted to any other integer type.

http://en.cppreference.com/w/cpp/language/implicit_cast#Integral_conversions

Signedness of char is implementation-dependent

Is char signed or unsigned by default?

And because of the following:

If the destination type is signed, the value does not change if the source integer can be represented in the destination type. Otherwise the result is implementation-defined.

The behavior of the type conversions is wildly implementation-specific.

So the answer is maybe. For small values of n you're probably okay, but all bets are off once you run into truncation and signedness etc.

2

char ranges from -128 to 127. so u can pass an int with a value in the given range. if the value of int is out of this range an overflow occurs and undefined behavior is observed.

To know how it exactly works print the value of char u get in the function and see the behavior.

0
0

In C, char is nothing than a (bit bizarre) integer type. When calling your function, implicit conversion between the arguments are taking place and everything is in order.

Such an implicit conversion only works well, because prior to the use of the function, a prototype has been provided, so the compiler knows what the arguments have to be.

Using char for x looks straight forward to me, here, since it is an entity to be compared to the contents of a. For n I don't think that it is a good idea. Generally everything that is sizes or indices should use the semantic type size_t that is provided for such cases, be it in main or in event.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.