简体   繁体   中英

How would I write a function in C which adds two numbers?

I'm just starting out learning C. I am encountering a problem-- for practice, I am trying to write a function which consumes two number and produces the sum of these two numbers. I think my code is right-- however, I get an error when I run it in an online C compiler. Here is my code:

#include <stdio.h>

int my_add (int a, int b) {
    return a + b;
}

int main(void) {
    trace_int (2 + 3);
    trace_int (my_add (2, 3));
}

Why am I not able to get the sum of 2 and 3. Also, why won't my my-add function work?

The error message I get says: warning: implicit declaration of function 'trace_int' [-Wimplicit-function-declaration]. Later on, it says undefined reference to trace_int

you need to define the data type of trace_int ie" whether it is a function or a integer otherwise it would return an undefined reference error also You need to verify by printing the output on the screen to see whether your function is working.

#include <stdio.h>
int my_add (int a, int b) {
    return a + b;
}
int main(){
    int trace_int=my_add(2,3);
    printf("%d\n",trace_int);
    return 0;
}

First you need to actully assing the return of the add function to a variable. You need to use the equals sign:

int trace_int = my_add(2,3);

and then actually print that variable, in order to see the result:

printf("%i", trace_int);

If you don't know how to assign variables, you should learn that first before going into functions.

I think you need to add trace_int function like that:

void trace_int(int value){
    printf("%d\n", value);
}

You are doing well but please go through the concept of C programming as C is a very Native language. First you have to "declare" ie. tell the C compiler about any Variable you are using, then you are allowed to use it in your program.

On line 6:

trace_int (2 + 3);

You haven't told the compiler what trace_int is and you started using it and passing the values into it. That's not a good idea.

First you have to declare the variable as:

int trace_int;

then you can use it.

On line 7:

trace_int (my_add (2, 3));

You didn't use an equal sign = to store the value returned by the function my_add() . To store the value in variable trace_int use the = operator like this:

trace_int = my_add(2, 3);

I think that would resolve your problem.

You need to store the value of my_add() in the variable and then you need to print that variable as below:

#include <stdio.h>

int my_add (int a, int b) {
    return a + b;
}

int main(void) {
    
    printf("%d", my_add (2, 3)); //Print value directly No need to store seperatly
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM