2,114 views
1 1 vote
What will be the output of following programs and why ?

1)
void foo(float *);
int main()
{
int i = 10, *p = &i;
foo((float*)&i);
return 0;
}
void foo(float *p)
{
printf("%f\n", *p);
}

 

2)

int main()
{
char arr[] = "geeksforgeeks";
char *ptr = arr;

while(*ptr != '\0')
++*ptr++;
printf("%s %s", arr, ptr);

getchar();
return 0;
}

3)

int main()
{
int c=5;
printf("%d\n%d\n%d", c, c <<= 2, c >>= 2);
getchar();
}
Output:4 4 4
I am not getting why the 3rd one is 4,because 5>>2 will give 1

1 Answer

1 1 vote

1) At first i taking the value 10. But when value of integer i converted to float, the alignment of int converted to float pointer. So, that is not same as change of value from float to int. Alignment change in pointer makes value 0 in float.So, it will print 0.000000

2)main point of this program is

(++(*(ptr++)));//According to precedence this will be execution order

Here increment operator first incrementing value of the pointer and then incrementing pointer index. So, it will print hfflt....

3) . It is tricky one. Here precedence and associativity plays main role. <<= is right to left associative. So, after assigning 5 in c, it first calculates right shift value i.e., c >>= 2  and then left shift value. So, first value of 5 becomes 1 and then it becomes 4. All of these things done in one sequence point. So, all C will point to same and final value 4. It will print 4 when the sequence point ends.

http://www.difranco.net/compsci/C_Operator_Precedence_Table.htm

• edited by
Position:
Show:

Related questions

0 0 votes
0 0 answers
1.4k
1.4k views
shiva0 asked Jan 11, 2019
1,399 views
#include int main() { int i = 1; printf("%d %d %d\n", i++, i++, i); return 0; }
1 1 vote
1 1 answer
8.8k
8.8k views
Piyush mishra asked Dec 7, 2018
8,809 views
#include<stdio.h int main() { int a[]={1,2,3,4,5,6}; int *ptr=(int *)(&a+1); printf("%d",*(ptr-1)); return 0; }this program print = 6 but if we try#include<stdio.h int ma...
3 3 votes
3 answers 3 answers
3.5k
3.5k views
Rudra Pratap asked Jul 20, 2018
3,522 views
#include <stdio.h int main() { static int i=5; if( i) { main(); printf("%d ",i); } }
0 0 votes
0 0 answers
1.4k
1.4k views
ayush201 asked Dec 30, 2018
1,351 views
A weight-balanced tree is a binary tree in which for each node. The number of nodes in the left sub tree is at least half and at most twice the number of nodes in the rig...