## Saturday, February 26, 2011

### lvalue and rvalue.....

This topic is really confusing to the beginners as well a to the intermediate programmers as they dun mess with this error usually.......but it is very necessary to understand what they are and when they come in the program????
let us try to understand what is  an lvalue???
K&R Says:
"An object is a manipulatable region of storage; an lvalue is an expression referring to an object....The name 'lvalue' comes from the assignment expression E1 = E2 in which the left operand E1 must be an lvalue expression"

so,we can say that::
LValue must be a container i.e. which have ability to hold the data and in c there is one container and which is variable. Hence LValue must be a variable in c.It cannot be a
-->constant,
-->function,
--> or any other data type of c.

lvalue-->location value

Note-->For the assignment to be valid, the left operand must refer to an object that is it must be an lvalue. The right operand can be any expression. It need not be an lvalue.
For example:
int p;
declares p as an object of type int. When you use p in an assignment expression such as:
p=7;
here p is an expression (a subexpression of the assignment expression) referring to an int object. The expression p is an lvalue.
Suppose you switch the left and right operands:
7=p;
Here the compiler will generate the errror.Although 3 is an expression but it is not a lvalue beacuse a constant can't be a lvalue rather it is an rvalue because it does not represent an object it just represent a value........

What is an rvalue???
rvalue is described as the value of an expression.....
more interestingly::lvalues are the subset of rvalues...that is all lvalues are rvalues but all rvalues are not lvalues....
An rvalue can be:
-->any C constant
-->any variable
-->function which returns a value
we can understand lvalue errors by generating them in our programs::so here are some question with explanation which generates lvalue required error;
1.)
void main()
{
int a=10;
7=a;
7=10;
}
Explanation:an integer constant can't be an lvalue...
2.)
void main()
{
const b=55;
b=70;
}
Explanation:a constant can't be an lvalue.
3.)
struct student
{
char *name;
int age;
}stu;
void main()
{
stu={"milan",21};
}
Explanation::Data types other than basics can't be lvalue..
4.)
#define VAL 10
void main()
{
VAL=50;
}
Explanation:macro constants can't be an lvalue...
5.)
enum {ONE,TWO};
void main()
{
TWO=2;
}
Explanation:enum constant can't be lvalue;

Now have a look at Rvalue:
#include<stdio.h>
#define num 10
void show();
enum {KING,QUEEN};
int main(){
int x=2; //RValue can be a constant.
float y=9.0;
x=num; //RValue can be a macro constant.
x=KING; //RValue can be a enum constant.
y=add();//RValue can be a function which return a value
y=show(); //RValue can't be a function which does not return any value
return 0;
}
Explanation::you can explain easily now.
more examples in the next post..........

## Wednesday, February 23, 2011

### A question on main.......

A few days back while playing with the programs i got stucked at the following program::

void (main(main))
{
printf("main=%d",++main);
}

that was the multiple choice question and there was an option compilation fails ,i smartly tick that and moved on to the next question ,but after doing all the question when i was checking my result i got 6/7 then i saw what went wrong because according to me the questions were simple....then i ran this on the machine instead of my mind and amazingly got that compiled without any error  and the output was:
main=2

I was amazed by seeing the answer,so started to find how it compiles,then i checked with other functions also and got the reason why void (main()) compiles without any error,but the solution of this question was the mystery again that is why void (main(main)) compiles....then i tried further to get the answer.......
after a little exploration i came up with the common misconception that main() does not accept any argument instead it can take any number of arguments.
then i take a lok at the standard for the main declaration and found this..
then i got why void (main(abc)),void main(main(abc,def,ghi,jkl)) or with any number arguments compiles under C89 because under C89 main() is acceptable and can take any number of arguments....
and i knew that main can be used as a variable name or identifier and is not treated as a keyword....so i come to know that  why void (main(main)) compiles??? because main can take any number of arguments under C89 and main can be used as a variable name or identifier ....

then again i stucked why the output is 2 that is why main equals to 1 ........then i tried the following code:

void (main(a,b,c,d))
{
printf("a=%d,b=%d,c=%d,d=%d",a,b,c,d);
}

and the output is:
a=1,b=garbage,c=garbage,d=garbage

Then i tried that on three different compilers that is turboc,dev and gcc on all the compilers it gives 1 for the first argument and garbage for the others the reason for this is still a mystery for me ....
anybody if knows why the first argument value is always 1 please post the reason as comment to this post.......and if you found this useful please rate this post.........

### what standard says about main function....

Today I am going to talk about the main function declaration in the C standards.
Two C standard-->C89 and C99

Under C89:
main() is accetable..

Under C99 two forms of main are acceptable:
`int main (void)`
`int main (int argc, char *argv[])`

Under C89,:
The return statement at the end of main() is required.
whereas under C99:
If no return statement is present, return 0 is implied.

## Tuesday, February 22, 2011

### A common misconception...

Today i am going to dicuss about a misconception about function in the minds of beginners....
The common misconcption is to assume that the function of following prototype does not take any argument...
void check();
which is totally wrong ,instead the above prototype states that the function check can take any number of arguments....
-->Using the keyword void withing the braces is the correct way to tell the compiler that the function takes NO arguments.....
void check(void);

lets take an example.....
#include<stdio.h>
#include<conio.h>
void check();
void main()
{
check();
}
void check(int a,int b)
{
printf("We are on the right way now");
printf("a=%d,b=%d",a,b);
}

The above program will compile for sure,and the output will be.
output:
We are on the right way now
a=garbage,b=garbage

Now we can see this is compiling and running because we have declared function check to take any number of arguments.....
if we call check by saying check(10,20);  the output will be:
We are on the right way now
a=10,b=20
And  we can call check by saying check(10,20,30,40,50,60,70) that is with any number of arguments...

Now change the prototype with void check(void);...now you can't use the above stuff.......

### small braces with functions......

While playing with the programs i certainly come up with the strange thing that samll braces does not matter with functions ....I mean to say that they does not matter if closed properly...
let us make this more clear by the help of an example....

#include<stdio.h>
#include<conio.h>
void func(int);
void main()
{
int f=20;
func(f);
getch();
}
void func(int num)
{
printf("num is:%d",num);
}

Everybody knows the output yes you are thinking right the output is:
num is:20

Now coming to the point,everybody knows about function declaration,function definition,function calling and i am not going to explain that...

change function calling statment to
(func(f));,
((func(f)));,
(((func(f)))); and any number of braces but the conditions is that the braces must be balanced....that is you can't say ((func(f))
you will get the same output,the same applies with function definition and function calling....

function declaration:
void func(int);,
void (func(int));,
void((func(int)));,
void (((func( int)))); and with any number of balanced braces are equivalent and does not lead to any compiler error....

function definition:
void func(int num),
void (func(int num)),
void ((func(int num))) and with any number of balanced braces are equivalent and does not lead to compiler error..

Are you amazed?????? And dun agree with me...run the follwing one and respond to this post.........

#include<stdio.h>
#include<conio.h>
void ((((func(int)))));
int (main())
{
int f=20;
clrscr();
((func(f)));
getch();
return 0;
}
void (((((((func(int n))))))))
{
printf("this is %d",n);
}

Note::missing braces in the above example may be a due to the editor ,please be sure that braces are balanced,because i know you are going to check it for sure.......

## Sunday, February 20, 2011

### Undefined Behavior.....

Kernighan and Ritchie wisely point out, ``if you don't know how they are done on various machines, that innocence may help to protect you.''

The C specifications are interesting because they leave many behaviors undefined. For example, if you try to use an uninitialized variable, the results are technically undefined.n some languages, the specifications might stipulate that if that ever happened, the program should gracefully halt with an error message or something. Or that all variables be initialized with default values as soon as they’re declared. The architects of C decided to leave it up to the compiler-makers to decide how to handle it. The reason is optimization. If the language’s designers required a graceful halt upon use of an uninitialized variable, then in order to be compliant, compiler-makers would have to build that into their compilers… which comes with a performance cost...

Some other behaviors which create undefined result:
• Division by Zero. In practice, this usually results in the program halting (possibly with a core dump), but it doesn’t have to, according to the C standards. 1/0 could be defined to be absolutely anything, and computing it might cause the computer to format its hard-drive– that would still be C-compliant.
• i++ += i + i++. Assume i starts at 0… what do you think i should become after this operation? The more general rule is: any time you try to read a variable twice within a computation in which you also write to that variable, the behavior is undefined.
• Trying to read or write from memory which hasn’t been allocated. Thus all the trouble with buffer overflows.

Example:
void main()
{
int i=10;
f(i++,i++,i++);
printf("i=:%d",i);
getch();
}
void f(int a,int b,int c)
{
printf("a=%d:b=%d:c=%d",a,b,c);
}

output:
undefined....

Explanation:The behavior of this program is undefined in the C standard..this depend on the compiler implementation and vary from compiler to compiler..The behavior is due to function call f(i++,i++,i++) due to the sequence points concept....

## Friday, February 18, 2011

### %n explored...

Yesterday one of my friends asked me about %n,i got shocked because i have nvr hear abt that...after searching about %n in printf i come up with the follwing info...

What is does::
1.)It Prints nothing,
2.)But write number of characters successfully written so far into an integer pointer parameter..

We will see the ouput by using printf,fprintf and sprintf ,the concept is same it nvr prints to anything whether it is :
-->standard ouput(console) in case of printf.
-->a file in case of fprintf.
-->a string in case of sprintf

With printf
#include<stdio.h>
#include<conio.h>
int main()
{
int *i,*j;
clrscr();
printf("milan%nkumar%n",i,j);
printf("\ni=%d",*i);
printf("\nj=%d",*j);
getch();
return 0;
}

output:
milankumar
i=5
j=10

Explanation:
let us take the format string in the printf.it is "milan%nkumar%n" whenever printf find the %n it looks for the integer pointer argument and writes the numers of characters sucessfully written so far at its location,so,when printf find the first %n it sets i with  number of character written on the stdout that is 5(milan)...now finding the another %n ,printf sets the j with the number of characre written so far on the stdout that is 10(milankumar)..
here we can see that %n nvr prints anything to the stream associated with the function...

With fprintf
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
int i=10,j=20,k=30;
int *p;
fp=fopen("c:\\test.txt", "w");
fprintf(fp, "Testing...%d%d%d%n",i,j,k,p);
printf("done....");
printf("\nnumber of characters written to the file are %d",*p);
getch();
return 0;
}

Output:
Testing...102030  /*data written to file:*/
done/*written to console*/
number of characters written to the file are 16 /*written to console*/

Explanation:
This example clears that %n is only associated with the printf in which it is used,it is not hardley attched with the stdout or printf ,it will always set the integer pointer with the number of the characters written to the stream that is used by the function..stream many be file,stdout,string etc..
so number of characters written to the file are 16(Testing...102030)..hence the output...

With sprintf
#include <stdio.h>
#include<conio.h>
int main()
{
char buff[50];
int a=34,b=50,*p;
clrscr();
sprintf(buff, "%d minus %d equals %d%n",a,b,a-b,p);
printf ("(%s) is the result of our sprintf",buff);
printf("\nNumber of characters written to the buff are:%d",*p);
getch();
return 0;
}

output:
(34 minus 50 equals -16) is the result of our sprintf
Number of characters written to the buff are:22

Explanation:
Now i think you can easily explain the output similarly in th eabove examples....
other wise feel free to mail me at milankmr@gmail.com

## Wednesday, February 16, 2011

### fun with printf...

Here are some interesting questions with printf ,have a look ....

(1)
#include<stdio.h>
#include<conio.h>
int main()
{
printf(5+"my name is milan kumar");
printf("\n");
printf(5+"my name is*milan kumar"+5);
printf("\n");
printf(5+"my name is milan kumar"-5);
printf("\n");
getch();
return 0;
}

output:
me is milan kumar
*milan kumar
my name is milan kumar

Explanation:
when we write "my name is milan kumar" that is a string ,it return the base address of the string and when we say 5+"some sting" then 5 get added to the base address and printf starts from the incremented address till the NULL is not found ....hence the ouptut

(2)
void main()
{
int a=30;
printf("%d"+1,a);
}

output:
d

Explanation:
As we have seen in the above example that whenever we write some string in the printf ,its base addres is taken ..so in this example when we write "%d"+1 base address of "%d" is taken and 1 is added to that and now printf will look as this :printf("d",a).now you can easily say why the ouput is d..

(3)
void main()
{
int a=30;
printf("%d:%d"+1,a);
}

output:
d:30

Explanation:
In this example,the format string is evaluted and turns out to be "d:%d" after incrementing the address.and you better know that how printf("d:%d",a) will be evaluted .hence the output..

(4)
void main()
{
int a=4;
printf(&a["hi! my name is milan kumar"]);
getch();
}

output:
my name is milan kumar

Explanation:
This output can be expalined under the knowledge that array subscripting is commutative in C...means that a[i] and i[a] both are same and rather equivalent to *(a+i).OR we say "milan"[2] and 2["milan"] are same and both yields l as the output....
so ,coming at the question:
&a["hi! my name is milan kumar"] is same as (&("hi! my name is milan kumar")[a]) and evaluated as
(&*("hi! my name is milan kumar"+a) ) ans as & and * are mutual cancelling operators this is same as saying
("hi! my name is milan kumar"+a) i.e. ("hi! my name is milan kumar"+4)..
so now printf will look as;
printf("hi! my name is milan kumar"+4) produces the output as described in question(1)..........

(5)
lets take a look at tricky one...

void main()
{
int a=7,b=8;
printf(&a["c is a big headache:%s???"],&b["hello!! check out your concepts"]);
getch();
}

output:

Explanation:
For the explanation of this question ,have one thing in mind that is the Protype of  printf or more importantly the arguments printf takes ,as we know printf takes first argument as the format string which is further used to format the argument followed by a comma ..as we write printf("%d%d%d",a,b,c) in this "%d%d%d" is the format string which is use to format the arguments which are a,b,c.. so,1st %d for a ,2nd for b and 3rd for c...

coming back to the question..in our question the format string is:&a["c is a big headache:%s???"] and we can take it as "big headache:%s???" as explained in the above question..so with the new format string printf will look as:
so,we can see that there is a %s in the format string to print the 1st argument which can be evaluated as :
"check out your concepts" as explained in the above question...so now printf will look as this:
now we can evalute the printf easliy just by replacing the %s with the first argument...ehnce the result....

(6)
#include <stdio.h>
int main()
{
int a=3, b = 5;

printf(&a["Ya!Hello! how is this? %s\n"], &b["junk/super"]);
printf(&a["WHAT%c%c%c %c%c %c!\n"], 1["this"],
2["beauty"],0["tool"],0["is"],3["sensitive"],4["CCCCCC"]);
getch();
return 0;
}

output:
Hello! how is this? super
That is C!

Explanation:
You can easily explain to yourself as explained in the above questions.......

## Tuesday, February 15, 2011

### Question on printf

What is the output of the following program?????????
void main()
{
int i=60,j=80;
printf("%d:%d");
}

Output:
80:60

Explanation:
As we have seen that All automatic variables and constants are stored into stack area in the data segment ..
so when we initialize the variables i and j they goes int the stack's initialized area...and printf pops the value from the stack if no 2nd argument is specified....and all we know that stack is LIFO so value 80 is printed before the 60.....

Now take a look at this:
void main()
{
int i=60,k,j=80;
printf("%d:%d:%d");
}

Output:
80:60:garbage value

Explanation:
This is again a bit tricky...we expect the result to be 80:garbage:60 which is not ..........
as we have seen that there are two portions in the stack area in the data segment one for intialized vaiables and other for uninitialized vaiables,and initialized variables lie above the uninitialized variable in the stack....as in the example k is not initialized it goes into the uninitialized area and comes out at the end..........

### Data segment......

A data segment is one of the sections of a program in an object file or in memory, which contains the global variables and static variables that are initialized by the programmer. It has a fixed size, since all of the data in this section is set by the programmer before the program is loaded. ...

Data segment is divided in to four parts.......

1.Data Area
All static and extern variables are stored in data area,it is permanent memory space and variable will store in memory until and unless program ends....

2.Code Area
Function pointer can only access code area. Size of this area is always fixed and it is read only memory area.

3.Heap Area
This memory area is use to allocate memory dynamically. In c we can allocate the memory space dynamically by using function malloc and calloc. It always allocates memory in the heap area. Its size is variable and depends upon free space in the memory

4.Stack Area

All automatic variables and constants are stored into stack area. Automatic variables and constants in c:

1.       All the local variables of default storage class.
2.       Variables of storage calls auto.
3.       Integer constants, character constants, string constants, float constants etc in any expression.
4.       Function parameters and function return value.

Variables in the stack area are always deleted when program control reaches it out of scope. Due to this stack area is also called temporary memory area.
It has two parts one for initialize variables and another for non-initialized variables.....All initialized variables are more nearer than non-initialized variables and vice-versa....

.

## Monday, February 14, 2011

### WAP to calculate and print 2 raise to the power 5 without using any digit in ur prgm

This is nothing just a trick,as we have looked that printf returns the number of charaters printed ....
and we know there is a pow function in the math.h library which returns the result of a number raised to other number.....

so the solution is........

#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
clrscr();
printf("power is %f",pow(printf("hi"),printf("hello")));
getch();
return 0;
}

output:
hellohipower is 32.000000

Explanation:
printf("hi") returns 2 ,printf("hello") return 5 and pow function returns the 2 raise to the power 5..........

Note....pow(arg1,arg2) evalutes from right to left thats why it prints hello first and then hi............

### what printf returns???????

Coming straightly to the point :the prototype of printf is:
int printf( const char *format ,…)
so the return type of printf is an int i.e. an interger value,
which is equal to the number of characters printed........
let us prove this by some examples:
(1)
void main()
{
int n;
n=printf("milan");
printf("the returned value from printf is %d:",n);
}

output:
the returned value from printf is:5

Explanation:
as the number of character in the world "milan" is 5,so the value returned is 5.....

(2)
void main()
{
int a=10;
printf("value returned is:%d",printf("%d",a);
}

output:
10value returned is:2

Explanation:
firstly the inner printf executes and printf the value of a i.e. 10,then it returns the number of chararters printed to the outer printf i.e.2(1 and 0 in 10)...and the outer printf prints the "value returned is:2",where 2 is the value retured by the inner printf.........

(3)
void main()
{
int a=2222;
printf("%d",printf("%d",printf("%d",a)));
}

output:
222241

Explanation:
In this example ,we will really come to that printf returns the actual number of characters printed by it,,firstly the innermost printf prints the value of a i.e 2222 and returns the number of characters printed that is 4,now coming to the second printf ,second printf got the value 4 returned by innermost printf and prints it and return 1(yes,1 not 5 because the value printed by second printf is just 4 not 22224),so the first printf gets the returned value from the second printf which is 1 and print the same...so the output is 222241...in which 2222 is printed by innermost printf,4 is printed by second printf and 1 is printed by the first printf.......

## Thursday, February 10, 2011

### Sequence points...

A sequence point in imperative programming defines any point in a computer program's execution at which it is guaranteed that all side effects of previous evaluations will have been performed, and no side effects from subsequent evaluations have yet been performed..

The C language defines the following sequence points:
·         Left operand of the logical-AND operator (&&). The left operand of the logical-AND operator is completely evaluated and all side effects complete before continuing. If the left operand evaluates to false (0), the other operand is not evaluated.
·         Left operand of the logical-OR operator (||). The left operand of the logical-OR operator is completely evaluated and all side effects complete before continuing. If the left operand evaluates to true (nonzero), the other operand is not evaluated.
·         Left operand of the comma operator. The left operand of the comma operator is completely evaluated and all side effects complete before continuing. Both operands of the comma operator are always evaluated. Note that the comma operator in a function call does not guarantee an order of evaluation.
·         Function-call operator. All arguments to a function are evaluated and all side effects complete before entry to the function. No order of evaluation among the arguments is specified.
·         First operand of the conditional operator. The first operand of the conditional operator is completely evaluated and all side effects complete before continuing.
·         The end of a full initialization expression (that is, an expression that is not part of another expression such as the end of an initialization in a declaration statement).
·         The expression in an expression statement. Expression statements consist of an optional expression followed by a semicolon (;). The expression is evaluated for its side effects and there is a sequence point following this evaluation.
·         The controlling expression in a selection (if or switch) statement. The expression is completely evaluated and all side effects complete before the code dependent on the selection is executed.
·         The controlling expression of a while or do statement. The expression is completely evaluated and all side effects complete before any statements in the next iteration of the while or do loop are executed.
·         Each of the three expressions of a for statement. The expressions are completely evaluated and all side effects complete before any statements in the next iteration of the for loop are executed.
·         The expression in a return statement. The expression is completely evaluated and all side effects complete before control returns to the calling function.

The Standard states that:
Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored.
Now,In an expression statement, the ``next sequence point'' is usually at the terminating semicolon, and the ``previous sequence point'' is at the end of the previous statement. An expression may also contain intermediate sequence points..

Undefined Behaviour::
"C guarantees that all side effects of a given expression is completed by the next sequence point in the program. If two or more operations with side effects affecting each other occur before the next sequence point, the behavior is undefined. "

just take a look at this...

#include <stdio.h>
int main()
{
int i = 5;
printf("%d %d %d\n", i, i--, ++i);
return 0;
}
The output is `5 6 5` when compiled with gcc and `6 6 6` when compiled with Microsoft C/C++ compiler.
take a look at another one....

#include <stdio.h>
int main()
{
int a = 5;
a += a++ + a++;
printf("%d\n", a);
return 0;
}
output as `17` with both the compilers...
The behaviour of such C programs is undefined. In the statement `printf("%d %d %d\n", i, i--, ++i);` and `a += a++ + a++;`, semicolon is the only sequence point.Such code may behave differently when compiled with different compilers.

From K&R. In Section 2.12 (Precedence and Order of Evaluation) of the book, the authors write,
C, like most languages, does not specify the order in which the operands of an operator are evaluated. (The exceptions are &&, ||, ?:, and ','.) For example, in a statement like
x = f() + g();
f may be evaluated before g or vice versa; thus if either f or g alters a variable on which the other depends, x can depend on the order of evaluation. Intermediate results can be stored in temporary variables to ensure a particular sequence.

One unhappy situation is typified by the statement
a[i] = i++;
The question is whether the subscript is the old value of i or the new. Compilers can interpret this in different ways, and generate different answers depending on their interpretation.