PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 9, 2022

[FIXED] How do you properly write a function that takes a parameter by reference in C?

 July 09, 2022     c, pointers, reference     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing