c - doubts using array and switch in? -


what role of statement ndigit[c-'0']? using ansi c.

#include<stdio.h> #include<string.h> #include<stdlib.h>  int main() {     int c, i, ndigit[10];     for(i = 0; < 10; i++)         ndigit[i]=0;     while((c = getchar())!= eof)     {         switch(c)         {             case '0' :case '1' :case '2' :case '3' :case '4' :case '5' :case '6' :case '7' :case '8' :case '9' : ndigit[c-'0']++;             break;         }     }     printf("digits=");     for(i=0;i<10;i++) printf("%d",ndigit[i]);     return 0; } 

c ascii character value (although stored in integer type). e.g. character '0' 48 in ascii, if getchar returns character '0' c have integer value 48.

c - '0' subtraction of 2 character values (ok, converts '0' integer 48 before subtracting), giving integer ready index array.

so char '1' becomes integer 1, char '2' becomes integer 2, etc.

it quick way of converting ascii character values integer values, known set of values. have strange results characters outside expected range '0'-'9' - e.g. if did character '+' -5 not array index. ok because switch statement checks in range '0' - '7'.


Comments

Popular posts from this blog

mod rewrite - Using "?" when rewriting the URL -

.htaccess: Transfer name to index.php if not directory public -

Admob integration with pygame in android -