How do they work?
Does -'0' always convert to int from char?
Can it convert from anything?
And same question about +'0', does it convert only from char to int, or from anything?

Thanks in advance :)

I guess I should not watch TV with the kids as I think "MY EYES! THE GOGGLES DO NOTHING!"

Here the compiler optimizes such away and I've yet to see C convert on its own from char to int. Are you a Java programmer?

These are character (integer values) so the + or - '0' will subtract the ascii value from the left side of the expression. If you are talking about a zero and not a capital Oh, that has a decimal value of 48, so you are subtracting or adding 48. Here is a link to the ascii chart for you to look at: https://duckduckgo.com/?q=ascii+table

Edited 11 Months Ago by rubberman

As Dani's own @rubberman has indicated ... the char '0' has the ASCII int value of 48

But you do not need to worry about memorizing that (48) value,
as you can convert form char to int
for the digits 0...9
very easily like this:

/* problem3.c */

#include <stdio.h>

int main()
{
    const int ary[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    const int size = sizeof ary / sizeof *ary;
    int i;
    char buf[256];
    const char* numStr = "123456789";
    const char* p = numStr;

    int sum = 0;
    while( *p != 0 )
    {
        sum += *p - '0';
        ++ p;
    }
    printf( "The sum for 1 to 9 is %d\n", sum );

    for( i = 0; i < size; ++ i )
    {
        buf[i] = i + '1'; /* OR: i+1 + '0'; */
    }
    buf[size] = 0; /* terminate C string with '\0' char ...*/

    printf( "\nHere are the digits 1..9 placed into a C string: %s\n", buf );

    fputs( "\nPress 'Enter' to continue.exit ... ", stdout );
    fflush( stdout );
    getchar();
    return 0;
}

Edited 11 Months Ago by David W

This article has been dead for over six months. Start a new discussion instead.