I have been using C for a couple of years now and I always thought about writing a small post about C tricks I learnt over the years, and here I am. This morning I basically came acros a website showing a few C tricks that I already used and I finally got the inspiration to write my C tricks as well.
The first tricks I have been using sometimes is the following :
1 |
int i = "ABCD"; |
This stores the hexadecimal values of ABCD into I which should set the values to 0x41424344 (A = 41, B = 42, C = 43, D=44). I used this trick a couple of times for debugging purposes since it is easier to find ABCD or 0x41424344 than another value.
2) The next C trick I have is the following :
1 2 3 4 5 6 |
int a = 1; int b = 2; a ^=b; b ^=a; a ^=b; |
In this short example, the xor function is used
XOR
0 | 0 = 0
0 | 1 = 1
1 | 0 = 1
1 | 1 =0
Applied to our values it gives us the following :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
a = 00000001 or 1 b = 00000010 or 2 a ^=b; 00000001 00000010 -------- 00000011 = a or 3 b ^=a; 00000010 00000011 -------- 00000001 = b or 1 Finally a ^=b; 00000011 00000001 -------- 00000010 = a or 2 |
As shown we inverted the values of ‘a’ and ‘b’ without using a third variable.
3) The third trick is about structures :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <stdio.h> typedef struct myStruct{ int x; int y; int z; }myStruct; myStruct ms={.x =1, .y=2, .z=3}; int main(void){ printf("test: %d",ms.x); return 1; } |
As shown, the variables of the structure have been initialized at compile time and not first at 0. You can also use
1 |
struct myStruct myStruct = {1}; |
which will initialize all the elements to 1;
That’s all I got/remember at the moment, if I come across some other cool tricks (that I used) I’ll just update the post.
Post a Comment