Some hidden gems in C lang that you might be unware of

2 Min. Read
Aug 6, 2017

C Programming C Programming

Most of us have come across with C language during the first couple of semesters in Engineering or IT degree; or some of us might use C in daily life for living. I have found some exciting features of C which I would like to share:

Multiple Indices in for statement

Out of all the operators, comma , is the one everybody forgets about. It is hardly used and mentioned in books and tutorials. But it has an amazing use though. Its used in for statement to let you have multiple indices.

Example:

1
2
3
4
5
6
7
8
9
10
11
  /* reverse: reverse string s in place */
  void reverse(char s[])
  {
    int c, i, j;
    for (i = 0, j = strlen(s)-1; i < j; i++, j--) {
      c    = s[i];
      s[i] = s[j];
      s[j] = c;

    }
  }

Note: However, the commas in function arguments are not the ,(comma) operators.

Emphasis on Static and Extern variables

There are four types of Storage Classes in C. viz. auto, register , static and extern .

static

In C the static keyword is used to limit the scope of the variable/function to the containing file. It means, the identifiers won’t be accessible in code defined in another file.

When you need to retain the value stored in a local variables during multiple calls to a function, then you qualify a local variable as **static**. If not defined explicitly, static variables are initialized with zero; also even if you desire to initialize it with some value, you can only initialize it with constants.

1
2
  static int var = 10; // is valid
  static int var = someFuncReturningConstant(); // is invalid

Since it’s a local variable you cannot call it by it’s name from another function; you will return the pointer and thus can only be read or modified using the pointer. It is declared and initialized only once, but, it ends when the thread/process ends.

Static variables are stored in the data segment of memory unlike regular variables in a function which are stored in stack segment.

Output:

1
2
3
4
5
6
7
  ./a.out
  the function is called 1 times
  the function is called 2 times
  the function is called 3 times
  the function is called 4 times
  the function is called 5 times
  the function is called 6 times

extern

Unlike static keyword, **extern** is used to only declare the variable rather than allocating memory. Just after declaring var, you cannot initialize it, you need to define it as well.

In case of function declarations, they are implicitly extern. But, incase of variables, you need to explicitly write extern keyword.


Some useful links

http://www.geeksforgeeks.org/static-variables-in-c/

See C’s memory models here