Search code examples
cescapingc-stringsstring-literalsstrlen

How does strlen works in this case?


See the following code:

#include<stdio.h>
#include<string.h>
int main(void)
{
    printf("%lu",strlen("\\n"));
}

I know that the output would be 2 but confused whether \\ would be the first character taken into account and then n or \ would be the first count and \n would be the second?


Solution

  • "... But I am confused whether \\ would be the first character taken into account and then n or \ would be the first count and \n would be the second?"

    "\\" is the representation for the '\' character inside of a string literal.

    Thus, The first character of the string literal "\\n" is '\' and 'n' the second.

    You can make an experiment by using printf("\\n");. The output would be \n, not \(line feed).