Search code examples
cstringchar

Adding and subtracting strings and characters in C


I saw a question which had code snippet in C like this

#include <stdio.h>

int main() {
    char s[] = "MANIPAL2022";
    printf("%s", s+s[4]-s[3]);

    return 0;
}

which returned:

2022

I am not able to understand what is being done here and how is the adding of characters showing these values.

Moreover a string of the same length like WESTHAM2022 returned nothing

I tried to understand the pattern for this and for char s[] = "WESTHAM2022" printf("%s", s+s[5]-s[3]); The compiler returned some garbage value !)�U

And for

char s[] = "WESTHAM2022";
    printf("%s", s+s[2]-s[3]);

it returned 9WESTHAM2022


Solution

  •  s+s[4]-s[3]
    ="MANIPAL2022"+'P'-'I'
    ="MANIPAL2022"+80-73
    ="MANIPAL2022"+7
    ="2022"
    

    Here the last step is how pointer works.

    With s = "WESTHAM2022", s+s[5]-s[3] = s-19, pointing at an undefined area, thus it can return anything or crash