The meaning of the name of a function in C

Consider a ordinary code:

#include <stdio.h>

int x;

int func(int a){
    x++;
    return a;
}

int main(){
    int a = 1;
    int n = func(a);
    printf("x = %d, n = %d", x, n);
    return 0;
}

It will print x = 1, n = 1 as expected.

But if I slightly edit the code as follows:

#include <stdio.h>

int x;

int func(int a){
    x++;
    return a;
}

int main(){
    int a = 1;
    int n = func;
    printf("x = %d, n = %d", x, n);
    return 0;
}

With the function not properly written, the complier does not report an error but prints x = 0, n = 4199760 instead.

What happened to the program?

Does the name of the function have any speical meanings?

Thank you.

>Solution :

Yes. In your second iteration, the line:

int n = func;

basically is stating "retrieve the memory address where function "func" has been placed and store that value into variable "n". That line of code is not calling your function. So, variable "x" is not being updated and remains at a value of "0", which gives you the output you see. And, if you happen to run your program again, the value for the memory address of your function could change and you might see a different value printed.

Hope that clarifies things.

Regards.

Leave a Reply