Implicit Function Declarations Will Bite

Is the following code correct in C?

#include <stdio.h>
int main () {
    int i = DoSomething();    /* does it work? */
    printf("%d\n", i);
    return 0;
}
int DoSomething (int num) {
    return 5;
}

I haven’t done any survey on this, but I dare to guess that most modern day coders would answer the above code would not compile. Reasons are obvious. DoSomething is used without being declared first and the parameter defined in the function signature is missing from the caller. At the very least, when I first saw it, I was convinced that it would not work.

However, it turns out that it is indeed legal1 C code (albeit legacy). Running it against gcc without any option produced no warning message, and executing the resulting binary did indeed produce an output of 5. This is known as the implicit function declaration rule.

So, how does this rule work? How does the compiler handle an unresolved function call? What are the pitfalls?

Continue reading Implicit Function Declarations Will Bite

Advertisements

Generate Pseudo-random Numbers Using LFSR

When performance is critical, it is essential to avoid even the slightest overhead.

I’ve recently had the chance to implement a test facility scanning through the DRAM unit on various devices to be used by the hardware team in testing if the DRAM can function properly in extreme temperatures. The test is very simple, just involving writing on each block of the memory and then reading back to confirm whether the data remains intact. Generating a sequence of pseudo-random addresses seemed best suited for this kind of task to ensure good coverage of each part of the memory.

Due to the need to traverse through a very large number of blocks in a reasonably short time frame, an efficient algorithm that could utilize the specific underlying hardware would be most desired. And so, here comes LFSR.

Continue reading Generate Pseudo-random Numbers Using LFSR

Tripped on C

Almost right after I got into programming, I fell in love with C++.

Its immensely powerful nature keeps fascinating me day after day, and I’m always hungry to pick up a new piece of C++ wizardry to appreciate.

Now, along the way of appreciating various C++ magic, I’ve also come to learn various things about C, such that static linkage limits function’s scope to its translation unit, a function can be implicitly called without being declared first, and how various pseudo-templates can be produced by employing layers after layers of macro hacks…

It’s great stuff and I love it. But I got carried away. At one point, I thought to myself that though I probably would never fully understand even two-thirds about C++, grasping most of C shouldn’t be that hard. After all, knowing function pointers, bit manipulations, and tricks here and there should be sufficient. Right?

And so, I dared to think I knew C.

Continue reading Tripped on C