Thursday, July 28, 2011

Forward Declaration vs Function Prototyping, What's the difference?

Valid Conditions
The following will be how we can get a successful compile.

This would be using Function Prototyping:

### BEGINNING OF FILE###
... // declarations of whatever you want

void INSERT_STRING (char b);

int main()
{
  INSERT_STRING("A");
}


void INSERT_STRING(char b)
{
  // Where INSERT STRING is literally implemented.
}
#### END OF FILE ####



This would be Forward Declaration.

### BEGINNING OF FILE###
... // declarations of whatever you want

void INSERT_STRING(char b)
{
// Where INSERT STRING is literally implemented.
}

int main()
{
INSERT_STRING("A");
}
#### END OF FILE ####

Now what this last one means, is that if you wish to use INSERT_STRING, it must be fully implemented above the calling function (in this case main).



### BEGINNING OF FILE###
... // declarations of whatever you want

void INSERT_STRING (char b);
void USE_INSERT_STRING();
int main()
{
USE_INSERT_STRING();
}

void USE_INSERT_STRING()
{
INSERT_STRING("b");
}
void INSERT_STRING(char b)
{
// Where INSERT STRING is literally implemented.
}
#### END OF FILE ####

This is because the function has been prototyped, when the compiler goes to use it it knows that some function exists that has such and such properties and then it won't complain.
When it finally hits that function it compiles it, I am pretty sure that later the compiler comes back to the USE_INSERT_STRING function and replaces the "pointer" (or however it knows where to go to "call" the function), with the location that INSERT_STRING finally ends up, but don't quote me on it, as I'm not 100% certain, and I don't know compilers that well. If someone can confirm I would appreciate it.




Error Conditions
The following will contain some examples of how we can fail to compile.

Post Declaration with No Prototype

### BEGINNING OF FILE###
... // declarations of whatever you want

int main()
{
INSERT_STRING("A");
}

void INSERT_STRING(char b)
{
// Where INSERT STRING is literally implemented.
}
#### END OF FILE ####


Gotcha
This time it is by another function then main. You might have thought you were safe, but this should fail as well.

### BEGINNING OF FILE###
... // declarations of whatever you want

void USE_INSERT_STRING()
{
  INSERT_STRING("b)");
}

void INSERT_STRING(char b)
{
  // Where INSERT STRING is literally implemented.
}

int main()
{
USE_INSERT_STRING();
}
#### END OF FILE ####

The above fails because again the compiler is trying to use the function INSERT_STRING in USE_INSERT_STRING, and since it's not been "forward declared" (declared before it's used), it fails.

No comments:

Post a Comment