c function pointer & user defined function identifier collision - c

i tested this simple program of function pointer.
#include <stdio.h>
#include <conio.h>
void ptr();
void fun()
{
printf("fun() is called\n");
}
void ptr()
{
printf("ptr() is called\n");
}
int main()
{
void(*ptr)();
ptr=fun;
ptr(); // Why it works fine?
//(ptr)();
void(*a)()=fun;
(*a)();
_getch();
return 0;
}
output:
fun() is called
fun() is called
I have a question that why the function call statement
ptr();
won't call user defined function ptr(), but calls fun() function?
Why parentheses around ptr isn't necessary?
What changes my program will require so my program displays output as following.
ptr() is called
fun() is called

When you define a local variable ptr inside main, it shadows the same name function ptr which is global. So when you call ptr(), it's the local function pointer ptr that is called.
To make the function ptr being called, you need to make sure the local variable ptr is out of scope, as this artificial example:
int main()
{
{
void(*ptr)();
ptr=fun;
}
ptr();
}

It is an application of the usual scoping rules; local variables hide global variables of the same name.
Or, more accurately, variables defined in an inner scope hide variables of the same name in any outer scopes.
And scopes are basically controlled by sets of braces around blocks of statements (simplifying a bit).
You can get GCC to warn you about such problems with -Wshadow.
The other part of the issue is that you can call functions via a pointer to function in (at least) two ways:
(*ptr_to_function)(); // Pre-standard notation
ptr_to_function(); // Notation allowed by standard C
So the call ptr(); is identical to (*ptr)(); in your program.
What changes does my program require to display:
ptr() is called
fun() is called
The simplest change is to remove the line void (*ptr)() = fun;.
You could also do something like:
#include <stdio.h>
void fun(void)
{
printf("fun() is called\n");
}
void ptr(void)
{
printf("ptr() is called\n");
}
int main(void)
{
void (*xyz)(void) = ptr;
void (*ptr)(void) = fun;
xyz();
ptr();
return 0;
}

Related

Calling a function within another function (except main())

Let's assume I have 2 functions other than the main(), respectively func1() and func2(). Is it possible for me to call func1() in func(2) without declaring it first? Or should I use a pointer to the other function and pass it as an argument? Thanks in advance.
_"Is it possible for me to call func1() in func(2) without declaring it first?"_
It depends on compiler, but generally this will not work. (see exclusion example at bottom of answer.)
Some scenarios that illustrate:
Scenario 1: Normally will not work as function is being referenced before being declared:
int main(void)
{
int ret = func1();
return 0;
}
int func1(void)
{
return 1;
}
int func2(void)
{
return func1();
}
Results:
9, 15 error: implicit declaration of function 'func1' is invalid
in C99. Make sure that you include the function prototype.
Scenario 2: As all required definitions occur in order, this will compile and run without issue:
char func1(void)
{
return 1;
}
char func2(void)
{
return func1();
}
int main(void)
{
char ret = func1();
ret = func2();
return 0;
}
Results:
Compiles and runs with no problem because both functions are defined before being called (both func2() called from main() and func1() called from func1)
Scenario 3: The best way is always to pre-declare functions using prototypes either in same file before functions are called or in a header file that is #included in any source file that uses them. This clears up any potential problems, especially for those that inherit the code for maintenance:
int func1(void);
int func2(void);
int main(void)
{
int ret = func1();
return 0;
}
int func1(void)
{
return 1;
}
int func2(void)
{
return func1();
}
Regarding your comment:
"...a statement in my book caused confusion, I thought it might be related to a difference of the version of the C compiler in the book and I am using."
Could be: Per comment below, pre-standard C function definitions are supported by some modern compilers (eg gcc) thus would compile scenarios 1 & 2 without issue if functions complied with the default function definition; eg:
int func1(void)
int func2(void)
Here is how you do it:
void func2(int code); // forward declaration
void func1(const char* str)
{
func2(str[0]); // a call to a declared function
}
void func2(int code) // the callee
{
printf("code: %d\n", code);
}

Testing a static function by mocking a non-static function it calls in C

I have
program.h:
static int doSomething(int input);
program.c:
#include "program.h"
void sendSomethingToSomewhere(int things);
static int doSomething(int input)
{
// other code
sendSomethingToSomewhere(things);
return x;
}
void sendSomethingToSomewhere(int things)
{
// bad stuff
}
I want to test the doSomething function by creating a file test.c. program.h and program.c MUST NOT be modified. I want to replace the implementation of sendSomethingToSomewhere in program.c for my own in test.c, so that whenever doSomething calls sendSomethingToSomewhere, "good stuff" executes instead of "bad stuff". How do I do this?
test.c:
#include "program.h"
void test1();
void sendSomethingToSomewhere(int things);
void test1()
{
int output = doSomething(4);
printf("%d", output);
}
void sendSomethingToSomewhere(int things)
{
// good stuff
}
What you're asking for isn't possible.
The function you want to test lives in the same file as the function it calls that you don't want called. If program.c can't be modified, there's no way to call doSomething without it calling sendSomethingToSomewhere.
If you want to be able to test doSomething in isolation you'll have to move it to a different source file from the one containing sendSomethingToSomewhere.

Functions in C language

This code is working good.
#include<stdio.h>
#include<conio.h>
void show()
{
printf("Show function");
}
void main()
{
show();
}
but this requires some more.
#include<stdio.h>
#include<conio.h>
void main()
{
show();
}
void show()
{
printf("Show function");
}
That is.. I have to declare a "Show" function in main.
why i need to do this?
You need to declare show before main because main calls show before it is defined. You can do this with a function prototype as shown below
#include <stdio.h>
// You reference show in main but the compiler will see main before show
// This is required to let the compiler know show will later be defined
void show();
void main()
{
show();
}
void show()
{
printf("Show function");
}
In the first example, when C enounters the function call to show, it already knows what arguments the function takes, because the definition of show is above the call in the file, and C just goes thru once top to botom. In the second example the when call to show is hot C hasn't yet heard anything about a function named show.
Your code is parsed from beginning to end in one pass.
The second snippet won't compile since the compiler doesn't know what show () is once hitting the call.
As a fix, you can use a simple forward declaration, telling the compiler the function's name and signature without telling it about its body straight away:
#include <stdio.h>
#include <conio.h>
void show(); // Now the compiler knows the function
void main()
{
show();
}
void show()
{
printf("Show function");
}
Such declarations typically happen within header files. The actual implementation may then be out into any translation file (usually grouped as well).
You can declare the function before main like this (or inside a header file):
#include <stdio.h>
#include <conio.h>
void show();
void main() {
show();
}
void show() {
printf("Show function"
Actually you are not declaring the show() function in main but you are calling the show() function from main.
A function has to be declared outside of the main function or before calling it.
Function declaration is required when you define a function in one source file and you call that function in another file. In such case you should declare the function at the top of the file calling the function.
(Your program may run with a warning of function not declared)
#include <stdio.h>
void show();
void main()
{
show();
}
void show()
{
printf("Show function");
}
Because in genuine recent C every function has to be declared or defined (perhaps in some header file) before being used.
So add a line (declaring show) like
void show(void);
before your main in the second example. It is not needed in the first example because show is defined before its first use.
Notice that <conio.h> is not a standard header (don't exist on POSIX systems)

C program confusing output

#include<stdio.h>
int main(){
int main =22;
printf("%d\n",main);
return 0;
}
output:22
I am defining main as function and variable both even though compiler is not giving error. It should give error "error: redefinition of ‘main’ " . I am not able to understand why this code is working.
It will not give you an error because main is not a keyword. but main is define 2 times - Scoping rules come into play.
The main function is in the global scope - while the variable main is defined within the function main scope. They're not at the same level, thus there is no conflict.
The int main=22; line tells the compiler to use (declare) the local variable main - there is no conflict / ambiguity.
Do
int main(){
return 0;
}
int main =22;
on the other hand and you'll get an error.
The declaration of main inside the function creates a new identifier in the scope of the function. It does not override the main function which is defined in global scope.
#include <stdio.h>
#include <string.h>
void stuff();
main()
{
int val = 10;
printf("from main: %d\n", val);
stuff();
printf("from main: %d\n", val);
stuff();
}
void stuff()
{
int val = 5;
printf("from stuff: %d\n", val);
}
It doesn't matter defining the int val many times as it matters in which scope it's defined, this will output 10 5 10 5 , no errror no bad behavior

How following c program works?

This is the program
void message();
int main() {
message();
printf("Cry,and stop the monotony");
return 0;
}
void message() {
printf("smile and see");
}
In this program message function is called in main() but it is defined after function main so if the program execution begins from top side then it should generate error but it still works?how? can someone explain me?
second one can I write this program like this:
void message() {
printf("smile and see");
}
int main() {
message();
printf("Cry,and stop the monotony");
return 0;
}
It can be compiled because the declaration
void message();
tells to the compiler that such a function exists and is defined somewhere. It is so called forward declaration. The compiler then finds it after main function.
Forward declaration is used sometimes to declare that some entity exists somewhere and is defined but not yet, here you state just that it exists and you would like to use it. In case of class forward declaration you can use a pointer and reference to class objects without including class definition. For example
file.h
class Something;
// not included but I can use a pointer or reference
// as long as I don't call methods on it
void function( Something const& s);
file.cpp
#include "Something.h" // now it is needed because I will call a function on s
#include "file.h"
void function( Something const& s) {
s.sing();
}
The first line
void message();
is a forward declaration. That tells the compiler that an implementation of that function exists and follows.
void message(); // This is the function declaration
int main(){
message(); // Calls message()
printf("Cry,and stop the monotomy"); // Prints this phrase
return 0;
}
void message(){ // This is the function definition
printf("smile and see");
}
That's all there is to this example.
NO this is unconventional:
void message() {
printf("smile and see");
}
int main(){
message();
printf("Cry,and stopthemonotomy");
return 0;
}
As per your First Code
void message();
int main() {
message();
printf("Cry,and stop the monotomy");
return 0;
}
void message() {
printf("smile and see");
}
The c++ compiler works from Top to Bottom Approach so it will first find the statement
void Message(); as this is a declaration of function so it treat it as a Forward Declaration.
and Search for the definition in remaining code.
And About the Second Code Block:
Compiler itself find the definition of function at the first line void message(){...}
So it treat as a declaration and Definition.

Resources