cstringpointers

Why does "\0" give integer in c


So I am learning C language and was trying to make a function which returns the length of string. In the if statement I mistakenly used "" instead of ''. So instead of comparing to char '\0' it was comparing to (string) "\0". Something like this

if(*newchar == "\0"){...}

Curiosly the compiler returned
warning: comparison between pointer and integer

Why does the "\0" is interpreted as integer by the compiler?

EDIT: Bellow is my code. Also my print statement was copied wrong it is printf("%d","\0"); which outputs a random number every time now that I tested.

#include <stdio.h>
#include <stdlib.h>

int stringlen(char *newChar)
{
    char newint = *newChar;
    bool flag = false;
    while (!flag)
    {
        newint = *newChar;
        newChar++;
        printf("%c", newint);
        if (*newChar == "\0")
        {
            flag = true;
        }
    }

    if (flag == true)
    {
        return 1;
    }
    else if (flag == false)
    {
        return 0;
    }
}

int main(void)
{
    char *newChar = "Some string WOOOw";
    int run = stringlen(newChar);
    printf("%c\n", *newChar);
    printf("%d", "\0");
    return 0;
}

And the bellow is the warning that compiler gives

 warning: comparison between pointer and integer
   13 |         if (*newChar == "\0")

The program compiles but it prints random symbolls


Solution

  • Why does the "\0" is interpreted as integer by the compiler?

    It's not. It's a string constant with type array of char, and when used in an expression it decays to a pointer to the first element of that array.

    Assuming *newchar has an integer type such as int or char, it is this that is being compared with the pointer which is the address of the first element of "\0".

    Also, the fact that the warning is stated as "comparison between pointer and integer" doesn't necessarily mean the left hand side is a pointer and the right hand side is an integer. It's just stating what the two types are.

    As for this:

    printf("%d", "\0")
    

    The %d format specifier expects an int as an argument, but you're instead passing char * (which was converted from a char array as above). Passing a parameter to printf that doesn't match the format specifier triggers undefined behavior. What likely happened was that the pointer value was reinterpreted as an integer, however because this is undefined behavior you can't depend on anything specific happinging.