Basic grammar for c

4 minute read

c is one of my favorite languages but it’s still not easy to use. Sometimes I forget some grammars and I’m also having trouble to remember the loop statement. It’s because I use various kinds of languages such as java, python, javascript, c#, etc. I’m trying to leave code snippets for using various languages ​​efficiently.

Datatype

Going by the standard, all that’s guaranteed is:

  • int must be at least 16 bits
  • long must be at least 32 bits
  • long long must be at least 64 bits

On major 32-bit platforms:

  • int is 32 bits
  • long is 32 bits as well
  • long long is 64 bits

On major 64-bit platforms:

  • int is 32 bits
  • long is either 32 or 64 bits
  • long long is 64 bits as well

If you need a specific integer size for a particular application, rather than trusting the compiler to pick the size you want, #include (or ) so you can use these types:

  • int8_t and uint8_t
  • int16_t and uint16_t
  • int32_t and uint32_t
  • int64_t and uint64_t

You may also be interested in #include (or ):

  • size_t
  • ptrdiff_t

Statement

switch/case statement

    switch (piSigNo)
    {
        case  SIGINT  :
            UserLog_(EMG, _F_L_, "Event Handler call [%d:SIGINT]", piSigNo);
            ExitProc_();
            break;
        case  SIGPIPE :
            UserLog_(EMG, _F_L_, "Event Handler call [%d:SIGPIPE]", piSigNo);
            ExitProc_();
            break;
        case  SIGILL  :
            UserLog_(EMG, _F_L_, "Event Handler call [%d:SIGILL]", piSigNo);
            ExitProc_();
            break;
        default:
            UserLog_(EMG, _F_L_, "Event Handler call [%d:XXXXXXX]", piSigNo);
            ExitProc_();
            break;
    }

String format

#include <stdio.h>
#include <string.h>

void main()
{
    printf("[%3s]\n", "abcd"); 
    printf("[%.3s]\n", "abcd");
    printf("[%.10s]\n", "abcd");
    printf("[%10.10s]\n", "abcd");
    printf("[%10s]\n", "abcd"); 
    printf("[%10.*s]\n", 3, "abcd"); 
    printf("[%-*.*s]\n", 10, 3, "abcd"); 

    long ll = 5;

    printf("[%*.*ld]\n", 10, 10, ll);
    printf("[%.*ld]\n", 10, ll);
    printf("[%*.ld]\n", 10, ll);

    printf("[%-*.*ld]\n", 10, 10, ll);
    printf("[%-.*ld]\n", 10, ll);
    printf("[%-*.ld]\n", 10, ll);
}

Output

[abcd]
[abc]
[abcd]
[      abcd]
[      abcd]
[       abc]
[abc       ]

[0000000005]
[0000000005]
[         5]

[0000000005]
[0000000005]
[5         ]

Formatting

For int %d

For long int %ld

For long long int %lld

For unsigned long int %lu

For unsigned long long int %llu

fprintf:

%f -> double
%Lf -> long double

scanf:

%f -> float 
%lf -> double 
%Lf -> long double 

sizeof

#include <stdio.h>

void main ()
{
    printf("short (int)    : %d, unsigned short : %d \n", sizeof(short), sizeof(unsigned short));
    printf("int            : %d, unsigned int   : %d \n", sizeof(int), sizeof(unsigned int));
    printf("long (int)     : %d, unsigned long  : %d \n", sizeof(long), sizeof(unsigned long));
    printf("long long      : %d \n", sizeof(long long));
    printf("float          : %d \n", sizeof(float));
    printf("long float     : %d \n", sizeof(long float));
    printf("double         : %d \n", sizeof(double));
    printf("long double    : %d \n", sizeof(long double));
}

<Result : IBM AIX 5.3>

short (int)    : 2, unsigned short : 2 
int            : 4, unsigned int   : 4 
long (int)     : 8, unsigned long  : 8 
long long      : 8 
float          : 4 
long float     : 8 
double         : 8 
long double    : 8 

Base64 encoding

#include<stdio.h>
#include<string.h>
 
#define BAD     -1
#define DECODE64(c)  (isascii(c) ? base64val[c] : BAD)
 
static const char base64digits[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
char base64val[128];
 
void main()
{
    char    in_password[20+1], out_password[100+1];
    int    i;
 
    for (i=0; i<128; i++) {
        base64val[i] = BAD;
    }
 
    for (i=0; i<64; i++) {
        base64val[base64digits[i]] = i;
    }
 
    strcpy(in_password, "ABCDEFGHIJKL1234");
    memset(out_password, 0x00, sizeof(out_password));
    encode_base64(out_password, in_password, strlen(in_password));
    printf("in=(%s), %d, out=(%s), %dn", 
    in_password, strlen(in_password), out_password, strlen(out_password));
 
    exit(1);
}
 
encode_base64(unsigned char *out, unsigned char *in, int inlen)
{
    for (; inlen >= 3; inlen -=3)                                      
    {              
        *out++ = base64digits[in[0] >> 2];
        *out++ = base64digits[((in[0] << 4) & 0x30) | (in[1] >> 4)];
        *out++ = base64digits[((in[1] << 2) & 0x3c) | (in[2] >> 6)];
        *out++ = base64digits[in[2] & 0x3f];
        in += 3;
    }
 
    if (inlen > 0)
    {
        unsigned char fragment;
 
        *out++ = base64digits[in[0] >> 2];
        fragment = (in[0] << 4) & 0x30;
 
        if (inlen > 1)  fragment |= in[1] >> 4;
 
        *out++ = base64digits[fragment];
        *out++ = (inlen < 2) ? '=' : base64digits[(in[1] << 2) & 0x3c];
        *out++ = '=';
    }
    *out = '';
}
 
int decode_base64(unsigned char *out, unsigned char *in)
{
    int len = 0;
    unsigned char digit1, digit2, digit3, digit4;
 
    if (in[0] == '+' && in[1] == ' ')   in += 2;
    if (*in == 'r') return(0);
 
    do {
        digit1 = in[0];
 
        if (DECODE64(digit1) == BAD)    return(-1);
 
        digit2 = in[1];
 
        if (DECODE64(digit2) == BAD)    return(-1);
 
        digit3 = in[2];
 
        if (digit3 != '=' && DECODE64(digit3) == BAD)   return(-1); 
 
        digit4 = in[3];
 
        if (digit4 != '=' && DECODE64(digit4) == BAD)   return(-1);
 
        in += 4;
        *out++ = (DECODE64(digit1) << 2) | (DECODE64(digit2) >> 4);
        ++len;
 
        if (digit3 != '=')
        {
            *out++ = ((DECODE64(digit2) << 4) & 0xf0) | (DECODE64(digit3) >> 2);
            ++len;
 
            if (digit4 != '=')
            {
                *out++ = ((DECODE64(digit3) << 6) & 0xc0) | DECODE64(digit4);
                ++len;
            }
        }
 
    } while 
 
    (*in && *in != 'r' && digit4 != '=');
 
    return (len);
}

Hex encoding/decoding

/*--------------------------------------------------------------------
 * Function     : simpleHexEncode
 * Description  :
 * Input param  : 
 * Output param :
 * Return value : int
 *-------------------------------------------------------------------*/
int simpleHexEncode(BYTE *msgdat, int msglen, char *msgout) {
    int idx;  
    int len = 0;
    char temp[2+1];
    memset(temp, 0x00, sizeof(temp));

    for (idx=0 ; idx < msglen ; idx++) {
        sprintf (temp, "%02X", msgdat[idx]);
        strcat(msgout, temp);
        len+=2;
    }   
    msgout[len] = 0x00;
    return len;
}


/*--------------------------------------------------------------------
 * Function     : simpleHexDecode
 * Description  :
 * Input param  : 
 * Output param :
 * Return value : int
 *-------------------------------------------------------------------*/
int simpleHexDecode(char *msgdat, int msglen, char *msgout) {
    int idx;  
    int pos = 0;
    char temp[2+1];
    memset(temp, 0x00, sizeof(temp));
    
    if (msglen % 2)
    {   
        return(-1);
    }   
    
    for(idx = 0; idx < msglen ; idx++)
    {   
        memcpy(temp, msgdat + pos, 2); 
        pos+=2;

        msgout[idx] = (char)strtoul(temp, NULL, 16);
    }   
    msgout[idx] = 0x00;
    return idx;
}

hostname

#include <stdio.h>
#include <string.h>
#include <errno.h>

int main() {
    char lsHostname[128];
    if (gethostname(lsHostname, 128) < 0)
    {   
        printf("gethostname error(%d:%s]\n", errno, strerror(errno));
        return -1; 
    }   
    printf("HOSTNAME:%s\n", lsHostname);
}

Tags:

Categories:

Updated:

Leave a comment