C programming tips
Tip#1) – Macro To Get Array Size Of Any Data Type.
The following macro will help you in getting the size of an array of any data type. It works by dividing the length of the array to the size of its field.
#define NUM_OF(x) (sizeof (x) / sizeof (*x))
#define num(x) (sizeof (x) / sizeof (*x))
int _tmain(){
int number[10] = {1,1,1,1,1,1};
char *teststr[20] = {"","","","","","","","",""};
printf("Size of number[10] is %d\n", num(number));
printf("Size of teststr[20] is %d\n", num(teststr));
}
Size of number[10] is 10
Size of teststr[20] is 20
Press any key to continue . . .
Tip#2) – Calculate Elapsed Time.
Friends, have you ever needed to calculate the time passed between two events? or You wanna keep a check on some function which is spuriously taking extra execution time than expected?
Here is the code snippet implemented using a set of macros to help you figure out how long something will take to run.
#include "stdafx.h"
#include <time.h>
#include <windows.h>
#include <stdlib.h>
clock_t startm, stopm;
#define BEGIN if ( (startm = clock()) == -1) \
{ \
printf("clock returned error.");exit(1); \
} \
#define CLOSE if ( (stopm = clock()) == -1) \
{printf("clock returned error."); \
exit(1); \
} \
#define SHOWTIME printf( "%6.3f seconds elapsed.", ((double)stopm-startm)/CLOCKS_PER_SEC);
main() {
BEGIN;
// Specify set of instructions for you want to measure execution time
Sleep(10);
CLOSE;
SHOWTIME;
}
Tip#3) – Smart Random Number Generator.
We have this rand() function defined in the stdlib.h for random no. generation. Did you use it and realized that every time you run your program but it returns the same result.
It’s because, by default, the standard (pseudo) random number generator is seeded with the number 1. To have it start anywhere else in the series, call the function srand (unsigned int seed).
For the seed, you can use the current time in seconds.
#include <time.h>
// At the beginning of main, or at least before you use rand()
srand(time(NULL));
Annexure:
For your note, the above code seeds the generator from the current second of time. This implies that if you expect your program to re-run more than once a second, the given code may not fulfill your requirement. A possible workaround is to store the seed in a file (that you will read later from your program), and you then increment it every time the program is run.
Tip#4) – Heard Of “Goes To-->” Operator?
Actually --> is not an operator. In fact, it’s a combination of two separate operators i.e. -- and >. To understand how “goes to” operator works, go through the below code snippet.
In the example, there is conditional’s code which decrements variable x, while returning x’s original (not decremented) value, and then compares the original value with 0 using the > operator.
int _tmain(){
int x = 10;
while( x --> 0 ) // x goes to 0
{
printf("%d ", x);
}
printf("\n");
}
9 8 7 6 5 4 3 2 1 0
Press any key to continue . . .
Tip#5) – Some Cool SCANF Tricks.
Find out some of the unheard scanf tricks that you must know.
scanf(“%[^,]”, a); // This doesn’t scrap the comma
scanf(“%[^,],”,a); // This one scraps the comma
scanf(“%[^\n]\n”, a); // It will read until you meet ‘\n’, then trashes the ‘\n’
scanf(“%*s %s”, last_name); // last_name is a variable
Tip#6) – Call Functions At Program Termination
Did you know about the atexit() API? This C API is used to register functions that can be automatically called when the program finishes its execution.
For example –
#include <stdio.h>
#include <stdlib.h>
void foo(void)
{
printf("Goodbye Foo!\n");
}
void bar(void)
{
printf("Goodbye Bar!\n");
}
int main(int argc, wchar_t* argv[])
{
atexit(bar);
atexit(foo);
return 0;
}
The following macro will help you in getting the size of an array of any data type. It works by dividing the length of the array to the size of its field.
#define NUM_OF(x) (sizeof (x) / sizeof (*x))
#define num(x) (sizeof (x) / sizeof (*x))
int _tmain(){
int number[10] = {1,1,1,1,1,1};
char *teststr[20] = {"","","","","","","","",""};
printf("Size of number[10] is %d\n", num(number));
printf("Size of teststr[20] is %d\n", num(teststr));
}
Size of number[10] is 10
Size of teststr[20] is 20
Press any key to continue . . .
Tip#2) – Calculate Elapsed Time.
Friends, have you ever needed to calculate the time passed between two events? or You wanna keep a check on some function which is spuriously taking extra execution time than expected?
Here is the code snippet implemented using a set of macros to help you figure out how long something will take to run.
#include "stdafx.h"
#include <time.h>
#include <windows.h>
#include <stdlib.h>
clock_t startm, stopm;
#define BEGIN if ( (startm = clock()) == -1) \
{ \
printf("clock returned error.");exit(1); \
} \
#define CLOSE if ( (stopm = clock()) == -1) \
{printf("clock returned error."); \
exit(1); \
} \
#define SHOWTIME printf( "%6.3f seconds elapsed.", ((double)stopm-startm)/CLOCKS_PER_SEC);
main() {
BEGIN;
// Specify set of instructions for you want to measure execution time
Sleep(10);
CLOSE;
SHOWTIME;
}
Tip#3) – Smart Random Number Generator.
We have this rand() function defined in the stdlib.h for random no. generation. Did you use it and realized that every time you run your program but it returns the same result.
It’s because, by default, the standard (pseudo) random number generator is seeded with the number 1. To have it start anywhere else in the series, call the function srand (unsigned int seed).
For the seed, you can use the current time in seconds.
#include <time.h>
// At the beginning of main, or at least before you use rand()
srand(time(NULL));
Annexure:
For your note, the above code seeds the generator from the current second of time. This implies that if you expect your program to re-run more than once a second, the given code may not fulfill your requirement. A possible workaround is to store the seed in a file (that you will read later from your program), and you then increment it every time the program is run.
Tip#4) – Heard Of “Goes To-->” Operator?
Actually --> is not an operator. In fact, it’s a combination of two separate operators i.e. -- and >. To understand how “goes to” operator works, go through the below code snippet.
In the example, there is conditional’s code which decrements variable x, while returning x’s original (not decremented) value, and then compares the original value with 0 using the > operator.
int _tmain(){
int x = 10;
while( x --> 0 ) // x goes to 0
{
printf("%d ", x);
}
printf("\n");
}
9 8 7 6 5 4 3 2 1 0
Press any key to continue . . .
Tip#5) – Some Cool SCANF Tricks.
Find out some of the unheard scanf tricks that you must know.
scanf(“%[^,]”, a); // This doesn’t scrap the comma
scanf(“%[^,],”,a); // This one scraps the comma
scanf(“%[^\n]\n”, a); // It will read until you meet ‘\n’, then trashes the ‘\n’
scanf(“%*s %s”, last_name); // last_name is a variable
Tip#6) – Call Functions At Program Termination
Did you know about the atexit() API? This C API is used to register functions that can be automatically called when the program finishes its execution.
For example –
#include <stdio.h>
#include <stdlib.h>
void foo(void)
{
printf("Goodbye Foo!\n");
}
void bar(void)
{
printf("Goodbye Bar!\n");
}
int main(int argc, wchar_t* argv[])
{
atexit(bar);
atexit(foo);
return 0;
}

Comments
Post a Comment