Home > Enterprise >  Operations with Characters and Integers in C
Operations with Characters and Integers in C

Time:02-02

I am new in programming Language and I need your help here. I am here studying someone's code and I can across with these expressions, my doubt is how is the operation done here, given that a character and an integers are two different data types? How will the integer type hold the character value?

Thanks

int line, col;
char ch;
scanf("%d%c", &line, &ch);
//line--;
col = ch - 'A';

CodePudding user response:

At the fundamental level, every type in C (be it char, int, uint32_t, short, long...) is represented by bytes, and is 'numerical' in form. You can subtract them from each other / add them together in whichever combination you like - as long as you store the resulting value in a variable of a type which is big enough to hold it - otherwise it will cause a buffer overflow.

In your example, since a char type is represented by a single byte, and an int is composed of 8, the result of this subtraction will simply be stored in the right-most byte of an int (however, depending on if you're dealing with an expression which will yield a negative value, then the representation of the int in memory will be slightly different - look into 2's complement if you're interested).

CodePudding user response:

When you subtract two characters and put them in a variable of integer type, in fact the ASCII code of the two characters is subtracted. For example when you have: int col = 'D' - 'A' The value of col is equal to 3 Because ascii code of D is equal to 68 and ascii code of A is 65. So col is 3, however D & A were character.

  •  Tags:  
  • Related