1

If we try something like

char *str = "hello";
if (isalpha(str))
    printf("%s\n", str);

we'd get a segmentation fault, because isalpha() takes int whose value must be in the range of an unsigned char or EOF.

But why doesn't the compiler complain about passing a char * where an int is expected? If char * gets implicitly-casted down to int, we might lose data!

In fact, if we have something like

void doSomething(int i);

int main(void)
{
    char *str = "hello";
    doSomething(str);
}

void doSomething(int i)
{
    // some code
}

The compiler will give this warning:

warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]

Assuming -Wpointer-to-int-cast is enabled by default, what's the difference here?

2

It turns out that isalpha is defined as a macro in the ctype.h header file, in my case, according to this answer (by @ouah on Stack Overflow):

Add -Wsystem-headers to get the warning

From gcc documentation (emphasize mine)

-Wsystem-headers

Print warning messages for constructs found in system header files. Warnings from system headers are normally suppressed, on the assumption that they usually do not indicate real problems and would only make the compiler output harder to read.

1

If I understand your question correctly, then I would say that the warning is compiler specific. I'm not one with extensive knowledge on compilers but when I ran it on my mac using Coderunner it produced the following warning:

warning: incompatible pointer to integer conversion passing 'char *' to parameter of type 'int'

this result from passing the [-Wint-conversion] flag.

| improve this answer | |
  • I believe the -Wint-conversion option in clang is the same as -Wpointer-to-int-cast in gcc. The point is that this option is still passed and you get the warning when passing a char * to a function that accepts an int in one situation and you don't get it in another. – Kareem Sep 22 '14 at 3:59
  • I usually receive a warning for every single occurrence. Do you have an example where you only receive the warning in one situation but not another? – Christopher Clarke Sep 22 '14 at 4:11
  • I already gave an example in the question. If you try to call isalpha passing in a string, nothing would complain about it. – Kareem Sep 22 '14 at 4:18
  • Then this must really be compiler specific because I implemented your example multiple times within a test program and received a warning for every occurrence. My compiler even refers you to the specific line in the ctype.h file where isalpha is declared. – Christopher Clarke Sep 22 '14 at 5:44
  • I took a screenshot of compiling with both, clang and gcc. As you might have noticed, they both don't give any warnings on the argument passed to isalpha, but they do on the same argument that is passed to doSomething. – Kareem Sep 22 '14 at 6:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .