tags:

views:

44

answers:

2

What's wrong with this?

#include <stdio.h>

void main(){
    char *s="some text";
    printf("%d",is_in(s,'t'));

}

int is_in(char *s, char c){
    while(*s){
        if(*s==c) return 1;
        s++;
    }
    return 0;
}

I get the following compile time error with GCC:

test.c:9: error: conflicting types for ‘is_in’

test.c:9: note: an argument type that has a default promotion can’t match an empty parameter name list declaration

test.c:5: note: previous implicit declaration of ‘is_in’ was here

+1  A: 

You are incrementing the character, not the pointer. Change *s++ to simply s++. In addition, you have forgotten to forward-declare your function "is_in". One other note: you should probably make your string a "const char*" instead of "char*", and, IMHO, explicit comparison with '\0' and using indexes is clearer:

#include <stdio.h>

int is_in(const char*, char);
int main(int argc, char* argv[]){
    const char* str="some text";
    printf("%d",is_in(s,'t'));
    return 0;
}

int is_in(const char* str, char c){
    int idx=0;
    while ( str[idx] != '\0' ){
        if ( str[idx] == c ){
            return 1;
        }
        idx++;
    }
    return 0;
}
Michael Aaron Safyan
Oh yeah, sorry. I modified the program but still same error.
Prab
++ binds tighter than *, so *s++ should evaluate to *(s++). This should be changed to s++ but shouldn't be causing his error.
Bill Zeller
Right! After I put my function above main, I tested with both s++ and *s++. In both the cases my program is working as expected.
Prab
No, `*s++;` increments the pointer s. The `*` is not needed in this case, of course, because the value of the expression is being discarded, but that doesn't mean that it's "incrementing the character" -- `++` has higher precedence than `*` http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence
David Gelhar
"explicit comparison with '\0' and using indexes is clearer" <-- I'm sorry but I 110% disagree with you on both counts.
Billy ONeal
+6  A: 

Have you tried putting the is_in function above main?

Bill Zeller
Oh wow! It worked!!!! But why? As far as I know I can write functions below main as well. Can u please clarify me.
Prab
Functions in C need to be declared before they're used: http://en.wikipedia.org/wiki/Function_prototype
Bill Zeller
Oh, ok. Thanks!
Prab
Well...sort of. For older versions of C compilers would just assume all your parameters are ints and go on its merry way. That scheme worked OK if all of your parameters were indeed ints. Otherwise havoc generally ensued.
T.E.D.