Reputation: 145
I am trying find out the number of characters in a string using the strlen()
function. The user inputs a sentence and the code must display the number of characters in the string.
int l;
char string[64];
printf("Enter a statement: \n");
scanf("%s",&string);
l = strlen(string);
printf("%d",l);
The code runs incorrectly with the following warning : [Warning] incompatible implicit declaration of built-in function 'strlen'
I did find the correct code online, but what exactly is wrong with my logic ? A little help required.
Upvotes: 0
Views: 1771
Reputation: 213721
The reason for the warning is forgetting to include string.h
What the warning means in detail, is that in older C from the 90s, it was valid to use a function without declaring it. So if you didn't provide the relevant header like string.h where the declaration is found, the compiler would then "guess" what function format you want and try to silently declare the function "between the lines".
The compiler would have implicitly given you this:
int strlen (); // accepts any parameters
But the real and correct strlen
declaration is this:
size_t strlen (const char *s);
These aren't compatible types, hence the warning about incompatible declaration. The actual definition of the strlen
function matches the latter, but not the former, so this is a bug.
From the year 1999 and beyond, implicit function declarations were removed from the C language, since they were plain dangerous. The gcc compiler still allows obsolete style C though, if you configure it a certain way.
If you are a beginner, you should always compile with a strict and standard compliant setup:
gcc -std=c11 -pedantic-errors -Wall -Wextra
This will swap the mentioned warning for an error, which is nice since this was a program-breaking bug.
Upvotes: 2
Reputation: 11921
Observation, firstly
The code runs incorrectly with the following warning : [Warning] incompatible implicit declaration of built-in function 'strlen'
This is because you didn't include the necessary header for strlen
.
#include <string.h>
Secondly, here:
scanf("%s",&string);
string
is character array and array name itself address, hence while scanning &
is not required.
scanf("%s", string); /* remove & */
Also, always check the return value of functions like scanf
. Check the manual page of scanf()
to know what it returns. For example:
int ret = scanf("%s", string);
if (ret == 1) {
/* success, proceed further */
}
else {
/* proper error handling */
}
Upvotes: 7