I'm trying to make a indexOf function in C. The function must find the position of any letter OR word which given in parameters. But when i tried to use one them, the compiler would alert as "too few arguments". How can i do that? Thanks.
#include<stdio.h>
#include<conio.h>
#include<string.h>
int indexOf(char*, char*, char);
int main(){
char stuff[] = "abcdefghijklmopqrstuvwxyz";
printf("Result: %d", indexOf(stuff, 'b') );
printf("Result: %d", indexOf(stuff, "defg") );
getch();
return 0;
}
int indexOf(char *text, char *word, char letter){
if(word == DEFAULT VALUE)
// find the letter in the text
else if(letter == DEFAULT VALUE)
// find the word in the text
}
You cannot do that in C: the language does not support overloads or default parameters. The only thing that you can do to emulate this would be using variable number of parameters, but that would not work here, because you would need to pass an additional parameter indicating the type of the item being searched.
A better approach would be defining two functions
int indexOfChar(char *text, char letter)
int indexOfWord(char *text, char *wors)
or better yet, using the corresponding functions from the standard library - strchr
and strstr
.