retagged by
412 views
0 votes
0 votes

Consider the following code snippet:

#include <stdio.h>

void s1(int*, int);
void s2(int*, int);
void (*k[2])(int*, int);

int main()
{
    int a = 4;
    int b = 2;
    k[0] = s1;
    k[1] = s2;
    k[0](&a, b);
    printf("%d %d ", a, b);
    k[1](&a, b);
    printf("%d %d\n", a, b);
    return 0;
}

void s1(int *k, int q)
{
    int tmp = *k;
    *k = q;
    q = tmp;
}

void s2(int *k, int q)
{
    int tmp = *k;
    *k = q;
    q = tmp;
}


The output of the above program is :

  1. 4242
  2. 2222
  3. 4444
  4. 2424
retagged by

1 Answer

2 votes
2 votes
void (*k[2])(int*, int);

Read it with the clockwise spiral rule. k is an array of pointers to functions which take an integer pointer and an integer as an argument.

 

 k[0] = s1;
 k[1] = s2;

k[0] points to the function s1, and k[1] points to the function s2.

 

k[0](&a, b);

Means call s1 with the address of a; and b is passed by value.

s1 makes a = 2 and b remains unchanged (2) because it was passed by value.

So, print 2,2

 

k[1](&a, b);

Means call s2 with the address of a; and b is passed by value.

Since a and b both have the values 2, swap would be redundant.

print 2,2 again

 

Option B

Answer:

Related questions

3 votes
3 votes
1 answer
1
Bikram asked May 14, 2017
266 views
Consider the below $C$ code:#include<stdio.h int main() { char a[] = "gateoverflow"; char *p = a; printf("%s", p+p[3]-p ); }The output will be : gate eoverflow overflo...
5 votes
5 votes
1 answer
3