PoiNtEr->: Secrets Of C language

                             Difference between a dream and an aim. A dream requires soundless sleep, whereas an aim requires sleepless efforts.

Search This Blog

Tuesday, December 28, 2010

Secrets Of C language


I was solving problems some time ago and came to know some good facts about c and c++ and wrote some interesting codes.

1. A C program which can print the file name it is kept in ;) .

#include<stdio.h>

main(){

printf(“the source file name is %s\n”,__FILE__);

}

actually __FILE__ is a macro which stands for the file name the programme is kept in and the compiler does the rest.

2. Usage of assignment suppression operator in scanf – Suppose you have some crap input (the input is provided to you but that is not of any use to your program) then what normally we do is take a dummy variable and scan the input in that variable. Example -

int dummy;

scanf(“%d”,&dummy);

but there is one more method which can save memory and time

what you do is

scanf(“%*d”);

In this method, we provide a character * to the scanf function and by doing that; scanf will scan the input from standard input but it wont assign it to any variable. This is scanned in a buffer of sufficient size and you dont have to worry about that.

3. Printing something with variable width -

Suppose you are to print some formatted output in some program and for that sometime you require to print a variable in a fix width ..

for example if you have to pring an integar in width of 5 or more then you do

printf(“%5d”, var);

now if var is 10 it will append 2 leading spaces to complete the atleast 5 width rule.

now suppose you dont want leading spaces but leading zeroes, then here is another method to write the same -

printf(“%05d”,var);

now if var is 10 it will print 00010 and so on.

Another condition comes if the width in which we want to print the variable is not known at the compile time – suppose you want to print variable with a width which is contained in another variable, then we can use -

printf(“%*d”,x,var);

here x is the width length variable. Whenever we do this * operator .. then it looks for the next integar argument provided in the arguments and then assumes that it is the width in which the variable is to be printed.

Now if x = 2 then it will b the same as

printf(“%2d”,var); ..

this way we can work with this width thing pretty well.

If any of you guys know some nice facts about c or cpp language, then please post them as comments. Any gud suggestions related to things I posted are also welcome. Have Fun

No comments:

Post a Comment