Gil
Gil

Reputation: 19

Void function (C language)

I'm trying to run a very simple code using a void function, but no matter what I try or some error occurs, or the program doesn't print what it was supposed to. The code is

#include <stdio.h>
int main()
{
    int i,j;
    i = 1;
    j = 2;
    add(i, j);
    return 0;
}

void add(int i, int j) 
{
    printf("%d + %d = %d", i, j, (i+j));
}

I am trying to use void in other more complex program so I am using this very simple to discover how to make it.

Upvotes: 1

Views: 4261

Answers (2)

rafaelc
rafaelc

Reputation: 59274

Change the order so that add is read first

#include <stdio.h>

void add(int i, int j) 
{
    printf("%d + %d = %d", i, j, (i+j));
}

int main()
{
    int i,j;
    i = 1;
    j = 2;
    add(i, j);
    return 0;
}

Upvotes: 3

Ayushi Jha
Ayushi Jha

Reputation: 4023

You need to give a prototype (or definition) of a function before you use it in a program.

Definition

Shift the function add before main function:

#include <stdio.h>
void add(int i, int j) 
{
   printf("%d + %d = %d", i, j , (i+j));

}

int main()
 {
     int i,j;
     i = 1;
     j=2;
     add( i, j);
     return 0;
 }

Prototype

#include <stdio.h>
void add(int,int);
int main()
{
    int i,j;
    i = 1;
    j = 2;
    add(i, j);
    return 0;
 }

void add(int i, int j) 
{
    printf("%d + %d = %d", i, j, (i+j));
}

Upvotes: 6

Related Questions