Functions in C language - c

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)

Related

Why does my codeblock work in main() but not in its own function?

A block of code produces the expected results when placed directly within the body of main(), but not when split off into its own function and called from main().
This is my first real try at C programming. As an exercise, I figured I'd try using ncurses to get an intro screen with centered text. Nice and simple, ncurses did the trick since printf isn't really capable of it.
So, I figure the next step would be to compartmentalize it within its own function as a first step to splitting it off into a separate .c file. I figure this would be a good way to practice splitting up code and referencing via header includes with the prototype in a .h file. Well, I never got that far. The code block simply doesn't do anything when compiled and run as its own function.
By "doesn't do anything" I mean that when I run the compiled program, nothing appears on the screen and I simply get the prompt again.
This is the version that produces the correct results:
#include <ncurses.h>
#include <string.h>
int main()
{
char mesg1[]="Space Tycoon";
char mesg3[]="Press Any Key To Continue";
int row,col;
initscr();
getmaxyx(stdscr,row,col);
mvprintw(row/2-1,(col-strlen(mesg1))/2,"%s",mesg1);
mvprintw(row/2+5,(col-strlen(mesg3))/2,"%s",mesg3);
refresh();
getch();
endwin();
return 0;
}
...and the version that does not:
#include <ncurses.h>
#include <string.h>
void intro();
void main()
{
void intro();
}
void intro()
{
char mesg1[]="Space Tycoon";
char mesg3[]="Press Any Key To Continue";
int row,col;
initscr();
getmaxyx(stdscr,row,col);
mvprintw(row/2-1,(col-strlen(mesg1))/2,"%s",mesg1);
mvprintw(row/2+5,(col-strlen(mesg3))/2,"%s",mesg3);
refresh();
getch();
endwin();
}
int main(){
intro(); // not void intro()
}
because you want to call the intro function from your main. If you code void intro(); you just are declaring (see C11 §6.7.6.3) inside main that intro function (and then you'll better give its signature, e.g. write void intro(void);).
BTW your main has to return int. See C11 specification n1570 §5.1.2.2.1
Look also into some C reference site.

How can I use a declared but undefined function in C regardless?

So what I want to do is I want to create a kind of framework for myself in the future but I realized I can't do something. It goes like this:
void whenPressedQ();
void whenPressedW();
...
void checkPressQ(){
whenPressedQ();
printf("Q was pressed");
}
...
void whenPressedW(){
doThings();
}
Later I will define these functions and choose which of them to use.
Problem is I can't do this for the other functions if I haven't defined them below. I get an "undefined function" error. Is there any way I can solve this? I've tried using pointers to functions and check if it's null but it's the same thing.
You can pass pointers to callback functions, or wrap them in structures, then have the library pass back a pointer to a function that matches the signature later, even one that you will write in the future. This was how the first C++ compilers implemented virtual methods of objects.
If you just want the code to compile while you’re getting around to the unimplemented functions, you can create dummy stub functions to shut the linker up.
Update
Here are some examples of what I mean. Your question is somewhat ambiguous. If what you are asking is how you can declare functions that you intend to implement later, and still be able to compile the program, the answer is to provide stubs. Here’s a MCVE of your interface:
#include <stdio.h>
#include <stdlib.h>
/* In older versions of C, a declaration like void doThings() would turn
* type-checking of function arguments off, like for printf().
*/
void whenPressedQ(void);
void whenPressedW(void);
void doThings(void); // Added this declaration.
void checkPressQ()
{
whenPressedQ();
printf("Q was pressed.\n"); // Don't forget the newline!
}
void whenPressedW()
{
doThings();
}
// Stub implementations:
void whenPressedQ(void)
// FIXME: Print an error message and abort the program.
{
fflush(stdout); // Don't mix the streams!
fprintf( stderr, "Unimplemented function whenPressedQ() called.\n" );
exit(EXIT_FAILURE);
}
void doThings(void)
// Is nothing a thing?
{}
// Test driver:
int main(void)
{
whenPressedW();
whenPressedQ(); // fails;
// Not reached.
return EXIT_SUCCESS;
}
If you want to let the program dynamically select which function to call, that is more complicated, but you can do it with callbacks. Here’s a simple example.
#include <stdio.h>
#include <stdlib.h>
// This would ordinarily go in a .h file:
typedef const char*(*callback_t)(void); // The type of a callback function.
extern callback_t get_the_answer(void);
// This would ordinarily go in a .c file:
int main(void)
{
callback_t ask_the_question = get_the_answer();
printf( "The answer to life, the Universe and Everything is %s.\n",
ask_the_question()
);
return EXIT_SUCCESS;
}
// This would ordinarily go in another .c file:
static const char* the_answer_is(void)
{
return "42";
}
callback_t get_the_answer(void)
{
return &the_answer_is;
}
The error you are getting a linker error. If you are not trying to build an executable, then you can just compile and do not link. On Linux / OS X, you can pass the -c flag to clang or gcc. On Windows, you can pass the /c flag to cl.exe when compiling.
You can then link the object files directly later, or build a static or dynamic library out of them.

Violating static function in C

In one interview I was asked, if in one file A, some static function is defined and in file B you want to use this static function -- how you will use it?
My answers were:
declaring in .h file
But if we declare that in a header file, other files which will include this also have access to this static function.
wrapper concept: Declaring a new function newfun in file A, which will call static function and calling this newfun in file B.
But he was not satisfied with these answers.
Can you please provide me some better solution to violate static.
Perhaps they wanted to hear about function pointers?
You can create a pointer to the function, and call it using that pointer.
One possible scenario where this is reasonable is if you have a callback function that you don't want to be callable by everyone, and you give the pointer as an argument to some register_callback function.
Callback functions were used extensively, for example to let the user of a GUI API provide code for what should happen when a button is pressed. Nowadays, with object-oriented languages, it is more common to subclass a class and define or override methods, such as the Android View class and the method OnClickListener, but C# delegates are very similar to C function pointers.
To illustrate the principle, here is the source code (the file "B" in the original question) for some sort of library, where the main component is the do_stuff function:
#include <stdio.h>
#include "some_library.h"
void (*stored_callback)(void) = NULL;
void register_callback(void (*callback)(void)) {
stored_callback = callback;
}
void do_stuff(void) {
printf("Doing stuff...\n");
printf("Calling callback...\n");
if (stored_callback != NULL)
stored_callback();
}
This header, some_library.h, file shows the API of that library:
extern void register_callback(void (*callback)(void));
extern void do_stuff(void);
And here is how the library is used (the file "A" in the question):
#include <stdio.h>
#include "some_library.h"
static void my_callback(void) {
printf("Inside the callback!\n");
}
int main(void) {
register_callback(my_callback);
do_stuff();
return 0;
}
My interview answer would be "You can't."
(Because the question says "in file B you want to use this static function" and it didn't say you are allowed to modify file A.)
I'm assuming you don't have access to the source of the static function or else you could just remove the static keyword or expose the function via an exported wrapper or global function pointer.
You can still use the static function if you use objcopy to manually change the visibility on the symbol in the object file / library.
Suppose this is the (unaccessible) static function:
//static.c
#include <stdio.h>
static void fun(){
puts("Hello world");
}
Suppose you only have static.o, obtainable with gcc -c static.c.
Now, let's assume you want to link static.o with main.o made from
//main.c
void fun();
void main(){
fun();
};
To be able to link it, you need to turn
$ nm static.o
0000000000000000 t fun
U puts
into
0000000000000000 T fun
U puts
You can do that with:
objcopy --globalize-symbol=fun static.o global.o
Now you can link with global.o instead of static.o.
$ gcc main.o global.o && ./a.out
Hello world
filea.c
#include <stdio.h>
#include "filea.h"
static void hidden(void) { printf("inside hidden function.\n"); }
fxptr unhide(void) { return hidden; }
filea.h
#ifndef FILEA_INCLUDED
#define FILEA_INCLUDED
typedef void(*fxptr)(void);
fxptr unhide(void);
#endif
fileb.c
#include "filea.h"
int main(void) {
unhide()();
return 0;
}

c function pointer & user defined function identifier collision

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;
}

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