954,176 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Decleration and defination Problem

In the function declarations, the argument identifiers are optional.
In the definitions, they are required (the identifiers are required only in C, not C++).

#include<iostream.h>

void f(int);

int main()
{
f(10);
	return 0;
}

void f(int)
{
}


<< moderator edit: added [code][/code] tags >>

This works fine..where is 10 going??..how the compiler handles this??

SpS
Posting Pro
599 posts since Aug 2005
Reputation Points: 70
Solved Threads: 32
 
This works fine..where is 10 going??..how the compiler handles this??

The same as it would any other useless code, such as:

int y, x = 10;
x = 5;


In the case of calling a function with a parameter, the value is still passed -- just like it would be if the value were being used.

Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

The compiler needs to know what something is before it will let you reference it. Just as you have to declare a variable before you use it, you must declare a function before you use it.

Imagine the code as a conversation. What if you are receiving directions on how to get somewhere, and the person giving directions told you to take a left turn at a place that you've never heard of, let's call it Johnson's Emporium. You'd be a bit confused, and you'd end up getting lost since you don't know what to look for. Now imagine that the person told you ahead of time that Johnson's Emporium was 5 miles down the road from where you are now. You'd be able to find where you need to go at that point since you know what to look for.

Some compilers allow you to use undefined variables and functions. When they see something used that they don't know about, they go looking for a definition for it. C compilers don't work that way, they need to know what to expect. By using a function declaration, you are essentially telling the compiler that there will be a function by that name and that you will define it later on.

Why would you need to use a declaration you may ask. Why not just put all the function definitions about your main function? The answer is simple. Imagine a scenario where you have two functions, and each function makes a call to the other function. It would be impossible to compile such a program is you couldn't use declarations.

I know I got a bit wordy for such a simple question, but it's important to know why code is structured as it is.

chrisbliss18
Posting Shark
917 posts since Aug 2005
Reputation Points: 38
Solved Threads: 25
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You