Fast and easy way to do some multiplications

30 12 2011

Most of computers have the shift left instruction.

Shifting the bits by “x” positions to left, is equivalent to multiplication by x^2.

In this case…

int a = 4;
int b = 0;
b = a<<1;
/* Now, b value is 8 */
b = a<<2;
/* Now, b value is 16 */

That’s all folks!





Constant strings

19 12 2011

Usually I need to open a file stream or a file descriptor to write something in that.

I used to create a new string, concatenating the directory (usually some macro) with the file name.

Something like this:

#define DIR    "/tmp/alice/files/"
  
FILE *fs = NULL;
char filename[500] = {0};
  
snprintf(filename, 500, "%s/file.txt", DIR);
fs = fopen(filename, "a+");

But an easy way to do that is to use the facility of constant strings:
#define DIR    "/tmp/alice/files/"
  
FILE *fs = NULL;
  
fs = fopen(DIR "file.txt", "a+");

In my opinion, this way is easier to read and certainly faster.

Bruno Soares.





return_if_fail

16 12 2011

One thing that I like in GLib is this macro: “g_return_if_fail” and “g_return_val_if_fail”.

But if you don’t use GLib or you have your own trace system, you can create your own macro, something like this:


#define return_if_fail(expr) if (!(expr)) {trace("[%s] - expr '%s' failed", __FUNCTION__, #expr); return;};

#define return_val_if_fail(expr, val) if (!(expr)) {trace("[%s] - expr '%s' failed", __FUNCTION__, #expr); return val;};

And with this macro, you can change your way to check the intergrity of your variables:

Common way:


if(var == NULL) {
printf("var == NULL\n");
return 1;
}

You can use:


return_val_if_fail(var != NULL, 1);

PS.: if you don’t have your own trace function, you can just change the “trace” for “printf” or “fprintf” function.

This is an easy, fast and nice way to trace the problems.





First of all…

16 12 2011

I would like to say that… let’s try it again!

New blog with another focus. We’ll try write somethings about C, Linux, Embedded, etc.

I invited some friends to write over here, they are very good professionals and experts in their areas.

So… let’s do it!