What is a char data? a char data can be a numerical value? [closed]

1

What is char data, is that I do not know if I can give a number as a value.

    
asked by Juan 01.05.2017 в 16:06
source

3 answers

2

In general, the type char is oriented to store a " caracter " ( unit of text: normally a letter or digit or punctuation mark or space or ...). In practice, what is stored is the numerical code of the character in certain coding. In C, the char corresponds to a byte (which in turn corresponds -not strictly speaking, but practically speaking- to an octet = 8 bits).

So, yes, in C, in practice, a C a char can be treated as an 8-bit number - you can use it to store a number, you can do arithmetic with it. Example

#include <stdio.h>
int main(int argc, char **argv) {
   char c1,c2;
   c1 = 'a';
   c2 = 97;
   if(c1==c2) printf("iguales\n");
   else       printf("distintos\n");
   c1 = c1 + 3;
   printf("c1 como caracter: %c como numero: %d\n",c1,(int)c1);
   return 0;
}

Print

iguales
c1 como caracter: d como numero: 100

But

  • You have to be careful not to exceed the range (only 8 bits)
  • If you do arithmetic and comparisons, you should clarify if you are working with signed char (range: -128 to 127) or unsigned char (range: 0 to 255)
  • It is not good to mix the concepts (texts vs. numbers). If your char represents a textual character, then it is not good to assign a number to it, because that would imply binding you to a certain encoding.

In general, it is better to use int_8 u uint_8 if you want to store 8-bit numbers.

    
answered by 01.05.2017 в 17:12
0

Good morning,

The data type char corresponds in c ++ to character or string of characters, in response to your question, if you could assign it a number, but I would take it as a character , not as a value numeric, if you need to have variables of type number, use int for integers or float for real numbers.

Greetings, I hope your question helps me, I'll leave you a material of a very good course on youtube that could help you.

link

    
answered by 01.05.2017 в 16:21
0

Of course you can give it a numerical value, but remember something important, -128 to 127, I recommend using it as unsigned in case you do not need negative numbers and so you will have reach of

answered by 01.05.2017 в 20:13