Reputation: 558
Why my "C" code doesn't compile in Linux (compiler ggdb3, C99) but nice work in Visual Studio? Here message of error:
20:1: error: control may reach end of non-void function [-Werror,-Wreturn-type] }
#include <stdio.h>
// Function to determine if one character string exists inside another string.
int findString(char source[], char searching[])
{
int i = 0, j = 0;
for (; source[i] != '\0'; i++) {
if (source[i] == searching[j])
if (source[i + 1] == searching[j + 1] &&
source[i + 2] == searching[j + 2])
return i;
else
return -1;
}
}
int main(void)
{
int index = findString("a chatterbox", "hat");
if (index == -1)
printf("No match are founded\n");
else
printf("Match are founded starting index is %i\n", index);
return 0;
}
I've tried to edd in the function this but it doesn't help
if (source[0] == '\0')
return -1;
Upvotes: 0
Views: 89
Reputation: 17678
First C is not Python so you need to use brackets properly (not just indenting).
That said, the problem is with your findString()
function. Once you do put some brackets properly, you will that if (source[i] != searching[j])
the function does not have a return
statement - whereas it's expected to return an int
.
if (source[i] == searching[j])
{
...
}
// what if source[i] != searching[j]
// you do not have any return statement for a function returning int
Failure to return from a non-void function causes undefined behaviour.
Citing C11 (by rubenvb)
6.9.1 Function definitions
12 If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.
It's more clear with C++:
[...]Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.[...]
Upvotes: 1
Reputation:
It looks like you're actually just getting a warning, but since you've given the Linux compiler the command line argument -Werror it's treating the warning as an error. If you look in the compiler output for Visual Studio you should see a similar warning.
Upvotes: 2