Issue
I am searching this information for a while now. Searching around the internet, many sites says that a Function reference, is written like this:
//Example 1
#include <stdio.h>
void somma (int a, int b, int *c) {
*c = a + b;
}
int main (void) {
int a = 4;
int b = 2;
int c = 8;
somma(a, b, &c);
printf("Risultato somma: %d", c);
return 0;
}
But this, is what I have learnt at school:
#include <stdio.h>
void somma(int a, int b, int &c) {
c = a + b;
}
int main(void)
{
int a = 4;
int b = 2;
int c = 8;
somma(a, b, c);
printf("Risultato somma: %d", c);
return 0;
}
This actually confuses me, because if I try to compile a program (written like I learned at school), I get a compilation error, which involves the function itself:
[ripasso2.c 2019-08-25 21:19:47.684]
ripasso2.c:3:30: error: expected ';', ',' or ')' before '&' token
void somma(int a, int b, int &c) {
^
[ripasso2.c 2019-08-25 21:19:47.684]
ripasso2.c: In function 'main':
ripasso2.c:13:5: warning: implicit declaration of function 'somma' [-Wimplicit-function-declaration]
somma(a, b, c);
^~~~~
What am I doing wrong? Did I have a mix up with the pointer?
Solution
This:
void somma(int a, int b, int &c) {
is not valid C syntax. It's C++ syntax. If they taught you this in school as C, then it's wrong.
The compiler produces an error about this and then also warns you about the fact that the function somma
is not declared, because it could not be correctly processed. It's really just one error.
The valid C declaration is the first one:
void somma (int a, int b, int *c) {
If you want to compile the C++ version (the one using int &c
), then you must use g++
, not gcc
. You can install it with a simple sudo apt install g++
(assuming you are on Linux), and then you can compile the program just like you do with gcc
.
Answered By - Marco Bonelli Answer Checked By - Terry (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.