Posts tagged “programming”.

Badly punctuated parameter list in #define

Sometimes working with an old c compiler brings up painful, yet fun-filled days of making it speak the same language as you, and sometimes you just go “*$&%*$#&% you piece of sh** compiler”

I had one such moment today, and after I had returned to Zen (some soul-searching and some google searching), I realized it quite simple.


$ gmake
...
...
some_file.h:42: badly punctuated parameter list in `#define'
some_file.h:64: badly punctuated parameter list in `#define'
Failed to compile
$

This was caused by the following:


file: some_file.h
-----------------
...
...
#define LOG(...) {\ printf (##__VA_ARGS__); \
}
...
...

This works in most modern C compilers. However, if you happen to use one from the 80s (I exaggerate a little – not by much), it throws the error as above. You can fix this as follows:


file: some_file.h
-----------------
...
...
#define LOG(ARGS...) {\ printf (##ARGS); \
}
...
...

Source : http://nixscripts.blogspot.com/2010/09/badly-punctuated-parameter-list.html

Power of 2

It’s been a while since I’ve done anything except write code — lots of it. The last 20 days have been insane, and ofcourse to a take a break from writing code, I like to read code that others write. (You DO know that I’m crazy, right?!). In one of my futile attempts at clearing my google-reader reading list, I chanced upon a post by Veerabahu, on finding if a number is a power of 2 (or not).

As he writes, there is the simpleton O(n) solution (you will have to click-through for that), and the most elegant (yet) bitwise solution:

/*
 */
bool
is_power_of_2(int n) {
   return ((n & -n) == n);
}

The bitwise way to calculate the power of 2 is probably the most efficient in c like languages. Ofcourse for that, your language of choice needs to support it and should be more efficient that common math functions. The other way is to use some simple math.

Let’s say N, is the value, and you need to check if it is a power of two. Compute n = log N / log 2. If floor(n) == n, then N was a power of 2.

/*
 */
bool
is_power_of_2_pure_math_baby(int n) {
    /* address -ve numbers */
    if (n < 0)
        n = -n;

    double i = log(n)/log(2);      /* i = power of 2 */
    return (lower(i) == i);        /* check if perfect power of 2 */
}

This is obviously, a less efficient way of checking if a number is a power of 2, than using the bitwise method. However, it has a few advantages:

  1. It works exactly the same way for all values of n.
  2. It works exactly the same way for all integers (ie, n can be int8/16/32/64, long, signed or unsigned, and the same logic would work
  3. It is O(1) like the bitwise solution
  4. It is less cryptic (ie just basic understanding of math is reqd for grokking this solution)
  5. Finally, it can be extended in future to calculate if n is a power of *any value*, not just 2

Of course, the point Josh Bloch was making in interviewing engineers, was that he is interested in knowing the WHY of a solution. It does not matter if the algorithm is marginally less optimal or different. If you are an interviewer in your organisation, and you catch yourself asking a question like this, remember that if an engineer can reduce O(n) to O(1), stop with similar micro-skills test. Find out why she coded it the way she did. It will tell you a lot more about her skills than some algorithms/tricks that can be picked up in a couple a days, if not overnight.

Why does Java not support unsigned int? – Part 1

An interesting thing for me, is that if I am active on twitter during daytime in India (now that I’m here on vacation), I get to have some interesting conversations about design and development. Today, I chanced to talk about the lack of unsigned values support in Java.


  1. Veerabahu
    veechand is there unsigned int in #java support your answers
  2. Shivanand Velmurugan
    shiva @veechand nope. but use char instead. If you really want a type, you can define your own class backed by char
  3. Veerabahu
    veechand @shiva @surendrakumar defining a own class for unsigned..let me think over it.. but my main question is y #java didn’t support unsigned ?
  4. Shivanand Velmurugan
    shiva @veechand @surendrakumar the question actually is, why do you need unsigned?
  5. Veerabahu
    veechand @shiva @surendrakumar my answer so that in given 32 bit I could store wide range of numbers (given my application wont go negative)
  6. Surendra Kumar
    surendrakumar @shiva a lot of real life applications uses unsigned int. Example sales, money, hours, are all unsigned.

this quote was brought to you by quoteurl

Java is, by no means, a “new” language for anyone I know. However, we still try to write C/C++ like code using it. We approach it with all of the training of C/C++, and start micro-optimisation much before it is needed, and end up with hard to comprehend complex code.

I thought I will write a long-winded post about why unsigned int is not available in Java, and how to emulate it if you really need to, but I will leave that to more able hands.

The reason for lack of unsigned types in Java are:
1. The core of the Java language was designed to be simple. This meant leaving out anything that adds complexity that can be done without. unsigned types didn’t make the cut
2. Someone got lazy and didn’t bother to implement them, when the time came to make Oak into Java. (I wish leaving things out like this happen more in the industry).

Now, let’s examine why one requires unsigned types:
1. Represent business case values like salary or percentile etc
2. Store bitsets — each bit representing some state or option
3. provide the ability to store more value that one can in an signed, thereby requiring lesser in-memory size

Case 1 is a no brainer: As long as the value fits within the bounds of a 32-bit integer, you shouldn’t care. Unless you need to store a value greater than 2,147,483,647, you shouldn’t care if it is signed or unsigned.

Case 2 is a hack: This is a typical carry-over from the C world, where there are no true enum or bitset types. If you need this, consider using an Enum or BitSet (as the case be for the problem you are trying to address)

Case 3 is a delusion, and a sin: To a certain extent this is also something that was necessary and a good thing in C, and almost useless, and sometimes wrong to do in Java. The cost and the risk of implementing a type, particularly one that will require, new arithmetic semantics to be written, is never justified. The less new language syntax one invents, the simpler the code is. My rule of thumb is — if I’m extending the language, I delete that class, and re-write it to use only existing semantics. If that means re-writing 5 other classes, so be it. In the long run, that yields a better, compact, and clean system.

Now contrast that, with using a signed int, where you expect the value to be unsigned. Unless you need to store a value greater than 2,147,483,647 there is no reason or benefit for implementing an unsigned int. Even in that case, unless you expect that to be marshalled to a system implemented in another language (like C/C++) via rpc, you should be using a long.

The next time you get the urge to extend the Java language, by defining a class that the language left out — think twice if you really need it. If, after deliberation, you still think you need it, implement it, use it in your code, delete the implementation and re-write your code. Trust me, it won’t have affected the application much, but your code will be cleaner and simpler to understand.

That is worth every extra-line of non-resuable code that you write.

Peace.
-Shiva

The Holy Grail and the Programmer’s High

Dave Winer, the inventor of RSS, wrote today about twitter’s latest API update for supporting the lists feature

It turns out there’s an API call that retrieves the timeline for a list, and it works exactly like the API call that retrieves the timeline for an account. So much so that I didn’t even have to change the glue script, I pass in a different URL and it just worked > orig link

I wonder if there can be a better award?! Dave Winer applauding twitter?! I never thought I’d see the day ;) (Just kidding Dave). Dave’s right though. There is a certain high that you get when something just works (as it was intended). That is the high that we programmers live for. It’s like a runner’s high.

It doesn’t happen very often though. When you work on large enterprise applications where several hundred bugs invariably creep in. Decades of dragging along old code and scars from several re-designs is a norm. But, once every so often, you change a complex module, with nothing but your own understanding of how the code works (it most cases, the understanding itself is small miracle), and the change that you make, works in several of the cases at once — that moment is pure happiness. It completely makes up for all the months of slogging, and the bug-hunting

You cannot be a programmer, if you don’t live for that!