Wednesday, September 9, 2020

type casting : converting one type to another

 refer to hi.c in the previous post


type casting: convert characters to the ASCII number value that represents those characters


#include <stdio.h>


int main(void)

{

char c1='H';

char c2='i';

char c3='!';


printf("i% i% i%\n", (int) c1, (int) c2, (int) c3);

}



in reality, clang is actually smart enough that even if you don't explicitly cast the chars to ints, it will know that the casting needs to occur and implicitly cast the chars to ints automatically


#include <stdio.h>


int main(void)

{

char c1='H';

char c2='i';

char c3='!';


printf("i% i% i%\n", (int) c1, (int) c2, (int) c3);

}



source: cs50, lec2


hi.c

 #include <stdio.h>


int main(void)

{

char c1='H';

char c2='i';

char c3='!';


printf("%c %c %c\n", c1, c2, c3);

}



source: cs50, lec2



single quotes for char ; double quotes for string ......... C requires this

 char c1 = 'a';

string s1 = "apple";