in Programming in C retagged by
918 views
4 votes
4 votes

Consider the following two blocks of code, found in separate files:

/* main.c */
int main()
{
    int i=0;
    foo();
    return 0;
}
/* foo.c */
int i=1;
void foo()
{
    printf(“%d”, i);
}

What will happen when you attempt to compile, link, and run this code?

  1. It will fail to compile.
  2. It will fail to link.
  3. It will print " $0$ ".
  4. It will print " $1$ ".
in Programming in C retagged by
918 views

4 Comments

Yes, older versions of C have allowed the direct use of function names without declaration. I briefly discussed it in our C programming lecture.

 

You can find the complete notes link here – Lecture 5 C programming GO Classes

3
3

$ \large{\colorbox{yellow}{Detailed video solution of this question with direct time stamp}}$
All India Mock Test 2 - Solutions Part 1

0
0
Answer should be option B
0
0

2 Answers

3 votes
3 votes

If you run the programs as:
gcc main.c foo.c
./a.out

then you will get 1 as output

  • You won’t get compile time error as foo() being referred is being compiled as well, and so the definition would be known to compiler.
  • You may get warnings due to printf() definition not being available at compile time, but linker gets the precompiled object file from C-library.
3 votes
3 votes

/* main.c */

#include <stdio.h>

void foo(); // Declare foo before calling it

int main()

foo();

return 0;

}

/* foo.c */

#include <stdio.h>

extern int i=1; // Declare i as external

void foo()

{

printf("%d", i);

}

 

I think this  should be the corrected code.

Answer:

Related questions