1,216 views
1 votes
1 votes
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 votes
1 votes

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

Related questions

0 votes
0 votes
0 answers
1
shiva0 asked Jan 11, 2019
655 views
#include int main() { int i = 1; printf("%d %d %d\n", i++, i++, i); return 0; }
1 votes
1 votes
1 answer
2
3 votes
3 votes
3 answers
3
Rudra Pratap asked Jul 20, 2018
1,835 views
#include <stdio.h int main() { static int i=5; if( i) { main(); printf("%d ",i); } }