I have written a simple program that is supposed to add 1 and 53, and return 54. But apparantly it does nothing. No error, just nothing.
The file is saved as firstEx.c
, I compiled and run like this
$ gcc -o firstEx firstEx.c
$ ./firstEx
All goes fine, except I see no output. Can anyone help? (I'm totally new to C.)
Here's the code:
#include <stdio.h>
int main()
{
int var1, var2;
var1 = 1;
var2 = 53;
void add_two_numbers (int var1, int var2);
return 0;
}
void add_two_numbers (int a, int b)
{
int c;
c = a + b;
printf ("%d\n", c);
}
The line
void add_two_numbers (int var1, int var2);
is a function prototype, not a call to said function. It's unusual to see it in the middle of a function but it's certainly valid, since it's just a style of declaration as per the standard (ISO C11 6.7
).
To actually call the function, you have to use something like:
add_two_numbers (var1, var2);
You should also ensure the function prototype is within scope when you call it, by either providing a prototype beforehand or simply defining the function before you call it. I'd start with something like:
#include <stdio.h>
void add_two_numbers (int a, int b) {
int c;
c = a + b;
printf ("%d\n", c);
}
int main (void) {
int var1, var2;
var1 = 1;
var2 = 53;
add_two_numbers (var1, var2);
return 0;
}
If you wanted to keep the order of functions the same, a prototype approach could be done as follows:
#include <stdio.h>
void add_two_numbers (int, int);
int main (void) {
int var1, var2;
var1 = 1;
var2 = 53;
add_two_numbers (var1, var2);
return 0;
}
void add_two_numbers (int a, int b) {
int c;
c = a + b;
printf ("%d\n", c);
}
A couple of other things just to keep you thinking:
add_two_numbers
to add the numbers and return the result, rather than print out the sum. Perhaps a better name would have been print_sum_of_two_numbers
.add_two_numbers
function could be whittled down to the single line printf ("%d", a + b);
.main
could be reduced to add_two_numbers (1, 53);
.main
, it will return zero "automagically" if you drop out the bottom. Some people may still prefer to be explicit, and quite a few oldies like myself will put it in just from force of habit, but it's no longer necessary.With all those changes, you can end up with the far more succinct:
#include <stdio.h>
void print_sum_of_two_numbers (int a, int b) {
printf ("%d\n", a + b);
}
int main (void) {
print_sum_of_two_numbers (1, 53);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With