Thread: Why Using int as return type in Serialport?

  1. #1
    Registered User Daffodils's Avatar
    Join Date
    Jul 2009
    Posts
    2

    Why Using int as return type in Serialport?

    observed that most of the low level serial port routines using int as datatype instead of char .Can anybody explain why ?What is the dis advantage if we use char?
    example
    Code:
    
    void init_serial (void)  {               /* Initialize Serial Interface       */
      PINSEL0 = 0x00050000;                  /* Enable RxD1 and TxD1              */
      U1LCR = 0x83;                          /* 8 bits, no Parity, 1 Stop bit     */
      U1DLL = 97;                            /* 9600 Baud Rate @ 15MHz VPB Clock  */
      U1LCR = 0x03;                          /* DLAB = 0                          */
    }
    
    
    /* implementation of putchar (also used by printf function to output data)    */
    
      int sendchar (int ch)  {                 /* Write character to Serial Port    */
    
      if (ch == '\n')  {
        while (!(U1LSR & 0x20));
        U1THR = CR;                          /* output CR */
      }													 																																						
      while (!(U1LSR & 0x20));
      return (U1THR = ch);
    }
    
    
    int getchar (void)  {                     /* Read character from Serial Port   */
    
      while (!(U1LSR & 0x01));
    
      return (U1RBR);
    }

  2. #2
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    It's probably due to the fact that using an int instead of a char allows the function to return an error. The function can return a valid char if it is successful (since a char fits inside an int), but it can then return -1 if the function fails.

    Seeing code like this is pretty common:
    Code:
    #define EOF -1
    
    int getchar(void)
    {
        if(nothing_left)
            return EOF;
        else
            return somechar;
    }
    
    int main(void)
    {
        int ch;
        while((ch = getchar()) != EOF)
        {
            /* Handle the received char */
        }
        ...
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. About aes
    By gumit in forum C Programming
    Replies: 13
    Last Post: 10-24-2006, 03:42 PM
  2. Another weird error
    By rwmarsh in forum Game Programming
    Replies: 4
    Last Post: 09-24-2006, 10:00 PM
  3. Replies: 2
    Last Post: 03-24-2006, 08:36 PM
  4. getting a headache
    By sreetvert83 in forum C++ Programming
    Replies: 41
    Last Post: 09-30-2005, 05:20 AM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM