Unveiling Hidden Gems in the C Programming Language
Many of us encounter the C language during our early semesters in Engineering or IT programs, and some of us continue to use C in our daily work. In this post, I’d like to highlight some intriguing features of C that you might not be aware of:
Multiple Indices in the for
Statement
Among all the operators in C, the comma ,
is often overlooked and rarely discussed in books and tutorials. However, it has a remarkable use when it comes to the for
statement, allowing you to have multiple indices.
Example:
/* 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: Commas used within function arguments are not the same as the comma operator.
Emphasis on Static and Extern Variables
C provides four types of Storage Classes
: auto
, register
, static
, and extern
.
static
In C, the static
keyword is used to limit the scope of a variable or function to the containing file. This means that identifiers declared as static
won’t be accessible in code defined in another file.
When you need to retain the value stored in a local variable across multiple calls to a function, you can qualify a local variable as static
. If not defined explicitly, static variables are initialized with zero, and you can only initialize them with constants.
static int var = 10; // Valid
static int var = someFuncReturningConstant(); // Invalid
Since it’s a local variable, you cannot directly access it by name from another function; you must return a pointer to it. Static variables are declared and initialized only once, but their lifespan extends until the thread/process ends.
Static variables are stored in the data
segment of memory, unlike regular function variables, which are stored in the stack
segment.
extern
In contrast to the static
keyword, extern
is used to declare a variable without allocating memory. After declaring a variable as extern
, you cannot initialize it; you must define it elsewhere in your code.
For function declarations, they are implicitly considered extern
. However, for variables, you need to explicitly use the extern
keyword.
Some Useful Links
Discovering these lesser-known aspects of C can enhance your programming skills and help you leverage the language’s full potential.