Wednesday, December 5, 2007

Interesting C Program -19

Hey,
Its long since my last post. I am here, with a very unique program.

Observe the output of the following C program
CASE:1

void func(void);
int main()
{
if(0)
func();
return 0;
}

Does this compile? (Yes/No). The answer depends on the compiler you are using. In some compilers this will compile without any errors. How come? "func()" is not defined anywhere. How come it is running?

Some smart compilers have that intelligence to compile such codes. This program runs, because "if(0)" is never going to be true. So the statement that follows is will never be executed. So, it dont even bother to search where the "func" function has been defined.

Ok, lets play around with the same program. Try out the following program.
CASE:2
void func(void);
int x = 0;
int main()
{
if(x)
func();
return 0;
}

Alas! this is throws the following errors.


Compiling source file(s)...
file_2.c
Linking...
C:\Documents and Settings\Administrator\Desktop\CTIPS\my_proj\Debug\file_2.o(.text+0x28): In function `main':
C:\Documents and Settings\Administrator\Desktop\CTIPS\my_proj\file_2.c:65: undefined reference to `func'



Why the hell it is throwing linker errors?

Lets do some more modifications and try.

Try out the following program.
CASE:3

void func(void);
const int x = 0;
int main()
{
if(x)
func();
return 0;
}


Again this throws the same error.
Is there any way of running this program?
Yes, there are ways.

There is a small tweaking you need to do in the compiler settings.

Lets try out that.

I am using MingWStudio. Try out similar things in your compiler or the Makefile.

1. Go to Project->Settings.
2. Go to Compile tab
3. By default the Optimization level will be None.
4. Change the Optimization to Level 1 or Level 2 or Level 3 or Minimum Size.
5. Give OK.
CASE:4
Now Clean the program to remove some previous configuration and then build.

This will definitely run.

The explanation goes like this.
In CASE:1, since mine is a smart compiler, this will be compiled without any errors.
I am working on CASE:2, CASE:3 and CASE:4.

Meanwhile if somebody knows why CASE:2 and CASE:3 didnt work and CASE:4 worked, please do comment me.

1 comment:

Anonymous said...

When the optimization is turned off, the compiler will check the conditional statements and if there is a const value then it will act smartly, otherwise if the variable is not a constant then it will throw the warning since the value of the variable will be referred during the runtime. You may know that the const keyword doesn't make a variable constant instead it makes read-only. So even in your case 'const int a = 0' will not work as u expect. Try using macro... it will work because it make the variable as constant. Correct me if i'm wrong

Search Google

Books that I refer to...

  • The Complete Reference C, Fourth Edition
  • The C Programming Language