Thread: Beginner question

  1. #1
    Registered User
    Join Date
    May 2003
    Posts
    49

    Beginner question

    I'm having a bit of a hard time understanding the point of the type char. My book says it is used for storing characters like letters, punctuation marks. It gves some examples but they just confuse me more. I'm just not understanding something.

    Can someone give me an explanation as to what the type char does?

  2. #2
    Registered User
    Join Date
    May 2003
    Posts
    9
    You can store a single ASCII character in a variable of type "char". All other basic types are for storing numeric data (double, float, long, short, int). You can also use the char type in conjunction with arrays in order to store strings, i.e.:

    char myname[9] = 'Gsibbery';

    Variables of type char must be enclosed in single quotation marks as I have above.

    What in particular don't you understand about it?

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >Can someone give me an explanation as to what the type char does?
    char is the smallest amount of data you can hold in C, it represents a byte (not necessarily an octet which is 8 bits) and is most commonly used to hold character data (hence the name char). It helps to think of char as a little int that has special properties when its value is used as a value from the machine's character set.

    For example, the ASCII value for A is 65. When you assign the character 'A' to a char variable, the value it holds is 65, not 'A'. Only when you choose to have that value represented as a character (not a number) will it be treated as 'A'. On top of this, int and char are interchangeable, which emphasizes the fact that char is just a little int:
    Code:
    #include <stdio.h>
    
    int main(void)
    {
        int  i = 'A'; /* i's value is 65 */
        char c = 'A'; /* c's value is 65 */
    
        printf("sizeof(char) == %lu\n", (unsigned long)sizeof (char));
        printf("sizeof(int) == %lu\n", (unsigned long)sizeof (int));
        printf("char: %c == %d\n", c, c);
        printf("int: %c == %d\n", i, i);
        
        return 0;
    }
    The only difference is the number of bytes that i and c use.
    My best code is written with the delete key.

  4. #4
    Registered User
    Join Date
    May 2003
    Posts
    49
    I'm going to need it explained in simpler terms (since I'm just a beginner), if that's possible.

    It sounds like each letter (A, B, C, etc.) holds a specific numerical value, but I don't think that's it.

  5. #5
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >It sounds like each letter (A, B, C, etc.) holds a specific numerical value, but I don't think that's it.
    That's basically it, each character has a numeric value and the char data type holds that numeric value, but can be represented by certain constructs such as

    char c = 'A';
    printf("%c", c);

    as printable characters. In ASCII, 'A' is 65, but when you use %c with printf, 65 is represented as the printable character 'A'.
    My best code is written with the delete key.

  6. #6
    Registered User
    Join Date
    May 2003
    Posts
    49
    Ok, this is how I understand it...

    I use a letter to specify a number rather than simply using a number, thus, I have to learn what each letter's numeric value is.

    This can't be right, it doesn't make sense.

  7. #7
    Pursuing knowledge confuted's Avatar
    Join Date
    Jun 2002
    Posts
    1,916
    if you check http://www.asciitable.com, you might understand what Prelude means by that a little better if you don't yet get it.
    Away.

  8. #8
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >thus, I have to learn what each letter's numeric value is.
    You could if you wanted, but to use the numeric values results in non-portable code. Not everybody uses ASCII. However, C guarantees that you can use character constants of the following symbols
    Code:
    A B C D E F G H I J K L M
    N O P Q R S T U V W X Y Z
    
    a b c d e f g h i j k l m
    n o p q r s t u v w x y z
    
    0 1 2 3 4 5 6 7 8 9
    
    ! " # % & ' ( ) * + , - . / :
    ; < = > ? [ \ ] ^ _ { | } ~
    without any knowledge of the underlying numeric value. By character constant I mean any of the above in between single quotes:
    Code:
    /* 'A' is a character constant */
    /* In ASCII it means 65 */
    /* In EBCDIC it means 225 */
    /* This is portable across multiple character sets */
    char c = 'A';
    My best code is written with the delete key.

  9. #9
    Registered User
    Join Date
    May 2003
    Posts
    49
    I guess my problem is I don't see the need for it. Are you able to give me a small example of a way to put it to good use?

  10. #10
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >Are you able to give me a small example of a way to put it to good use?
    The only truly simple examples I can give are contrived, but you can read a file name from the user into an array of characters for later use. This also illustrates the interchangeability of int and char in most situations.
    Code:
    #include <stdio.h>
    
    int main(void)
    {
        int  ch;
        int  index = 0;
        char filename[256] = {0};
    
        ch = getchar();
    
        while (ch != '\n')
        {
            filename[index++] = (char)ch;
            ch = getchar();
        }
    
        printf("%s\n", filename);
    
        return 0;
    }
    My best code is written with the delete key.

  11. #11
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Doh! Beat by Prelude, but here's what I wrote to answer your question:
    Code:
    #include <stdio.h>
    
    int main(void)
    {
      int c;
      
      printf ("Enter the letter y: ");
      fflush(stdout);
      
      while ((c = getchar()) != EOF && c != 'y')
      {
        while (c != '\n' && (c = getchar()) != EOF)
          ;
        printf ("Try again: ");
        fflush(stdout);
      }
      
      return 0;
    }
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  12. #12
    Registered User
    Join Date
    Apr 2003
    Posts
    20
    I think that Tride wants you to explain it in simpler terms, he is a beginner after all, and frankly, I think your answers are too complicated for him (you are using loops and arrays, and he still doesn't understand char's) to understand completely. I will try and explain it as simple as possible.

    A char is a variable (the smallest kind) and it just happens to be that this variable holds text (also called strings). Its that simple. With this variable you can make a program 'store' or 'hold' the text "James", this variable is called a char because it is in text. A char could also be a single character, for example 'f'. Before you can assign a value to any char (its the same with all variables), you need to declare at the beginning of main. Here is an example of declaring a char varible named letter that holds the 'g' character:

    Code:
    #include <stdio.h>
    
    int main()
    {
           char letter = 'g';
    
    ..................
    You have to put single quotes ' ' when referring to a single character. Remember you don't always have to give a 'value' (a letter) to char, you can just declare it, and give the value later in the program. Example:

    Code:
    #include <stdio.h>
    int main()
    {
           char letter;
    ......................
    All the examples above have been of char's variables that can only 'hold' 1 character, but (as stated before) you can also use them to 'store' a word or more. In that case you have to declare them a little different, you do the same but you have to specify the number of memory (each letter takes 1 byte, so if you have 6 characters you would have to put 7, just add 1 to the number of characters (yes, a space is also a character). I know it is a little confusing but just for now follow me and learn this, you will later learn why exactly this happens). Here is an example of declaring a char variable to 'store' more than 1 character (in this case 19):

    Code:
    #include <stdio.h>
    int main()
    {
           char words[20];
    ......................
    You could also give tell the variable what to store right away. Example:

    Code:
    #include <stdio.h>
    int main()
    {
           char words[] = "I am the best";
    ......................
    In this case, you have to put in double quotes " " the text you want the varible to store. You also don't have to specify the number of characters in the text, the compiler does that automatically (you still have to put the [] ).

    Now that you now how to declare a char variable, I'll put an example of a use for the char variable. Example:

    Code:
    #include <stdio.h>
    
    int main()
    {
            char letter = 'h';
            char word[] = "Bond, James Bond"; 
    
            printf("The letter variable is holding %c, and the word variable is holding %s.",letter,word);
    
            return 0;
    }
    This simple program displays the 'characters' that each char variable is holding. The printf function displays text, and also variables, in this case char. But you have to specify what variable type it is supposed to display. If you have a char holding a simple character you put %c to tell the printf function to display the variable there, and if you have a char holding more than 1 character you put %s. But also have to specify which variable is supposed to be displayed, so you put at then end of printf, a comma , and the varible name (or names if you want to display more than 1 variable in a printf statement). I just explain it here so you can understand better, but I assume you already know what a printf function does.

    Now to sum all up, a char variable stores text, whether a single character or many. When you store more than 1 character in a char variable, it is called an array, a char array. Remember you don't have to memorize it all, it is just meant for you to understand better, you will get it as you start learning more C. Good luck!
    Last edited by James00; 05-21-2003 at 06:27 PM.

  13. #13
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    I really don't see how that's easier to understand. The explanation isn't a bad one, just you introduce many new concepts that you basicly say the others shouldn't have introduced.

    You introduce strings, but don't expound on what exactly a string is.
    You introduce arrays, without also mentioning how they work.
    You intorduce unsized arrays, again, not explaining how they work.
    Here is an example of declaring a char variable to 'store' more than 1 character (in this case 19):
    You say what it does, but not why. The reason you only have 19 available here is because you want to treat it like a string. A string has a null terminator (meaning that last character following the last "valid" place in the string, must be zero. Not the character zero, but a NULL, whose decimal value is zero).

    You also don't explain how string literals work, when you use one as per your code above my post.

    But that's another lesson for another time.

    Quzah.
    Hope is the first step on the road to disappointment.

  14. #14
    Registered User
    Join Date
    Apr 2003
    Posts
    20
    Yeah I understand what you mean, but let me explain. I have only started learning C a couple of months ago (in a sense I am also a beginner), and that is how I learned about the char variable, and I have always understood it perfectly clear. The approach you and all the others take (also almost every single programming book takes that same approach) (not necessarily a bad one, maybe even better than mine, but not for everybody) is to explain everything right away, and I have not learned it that way, and I find it easier the way I have learned it. He only needs to know that that a char is used to 'store' a string or a character, I don't need to explain in detail what a string really is (no need to flood him with info) he will learn shortly (just in another lesson, after he learns more about C, believe me, he will clearly understand it then). Also, I think that arrays are to advanced to him right now (I didn't really learn about arrays until much further down the road) so I just mention them. You want me to explain to him what the NULL byte does and why it takes a byte, I find it to advanced for him right now. Not that he won't understand it, or is not capable of, but you guys are trying to 'shower' him with a lot of info right now, just keep it easy for him to understand. That's how I have learned C (what I know of course!) and I understand everything perfectly! (up until where I am at). I find that the approach you use is to technical and is not appropiate for absolute beginners that have no programming experience. Your approach may be incredibly useful for some people, particularly to those with previous programming experience, but not for people like me and (I suppose) Tride .
    Last edited by James00; 05-21-2003 at 06:46 PM.

  15. #15
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    He only needs to know that that a char is used to 'store' a string or a character,
    Well the first two responses cleared this up for him.

    On a side note, a char does not hold a string. A char holds one single character. An array of characters can be used to old a string, also, a character pointer which points to allocated space can be used for strings. However, a single char does not hold a string. Just to be picky.

    On a side note, the first reply had an error in their array initialization, since they state to use single quotes for their string. This would be incorrect.

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Beginner: Linked List question
    By WeatherMan in forum C++ Programming
    Replies: 2
    Last Post: 04-03-2008, 07:16 AM
  2. Quick IF statement question (beginner)
    By jim.rattlehead in forum C Programming
    Replies: 23
    Last Post: 11-29-2007, 06:51 AM
  3. beginner question
    By Barrot in forum C++ Programming
    Replies: 4
    Last Post: 08-19-2005, 02:17 PM
  4. Question About External Files (Beginner)
    By jamez05 in forum C Programming
    Replies: 0
    Last Post: 08-11-2005, 07:05 AM
  5. Beginner on Win32 apps, lame question.
    By Templario in forum C Programming
    Replies: 3
    Last Post: 11-06-2002, 08:39 PM