brandoncraig
brandoncraig

Reputation: 197

Function assigned to a variable in C

I did a test :

test1.c

#include <stdio.h>
int main () {
   getchar();
}

test2.c

#include <stdio.h>
int main () {
   int c;
   c = getchar();
}

Both test1.c and test2.c produce the same result which wait for the user to type something.

My questions :

  1. In test2.c, I only assign a function of getchar() into variable 'c', and I never invoke/call the function , so why does it get invoked? The reason why I said it gets invoked is because when I run it, it produces the same result as test1.c

  2. I thought a function only gets invoked when we invoke/call it, just like in test1.c , I invoke the function of getchar(). But in test2.c , I never invoke the function, I only assign the getchar() function to variable 'c'

Upvotes: 0

Views: 99

Answers (2)

define cindy const
define cindy const

Reputation: 632

The opening and closing parenthesis after the name getchar in C means to call the function associated with the name getchar. Therefore, in both code snippets you are actually calling the function.

If you wanted to "assign" the function to a variable c, it would look like this:

int (*c)() = &getchar;

What you're really doing above is taking the address of getchar and assigning it to the function pointer c.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

In test2.c, I only assign a function of getchar() into variable c, and I never invoke/call the function, so why does it get invoked?

C makes a difference between a function name, which is getchar with no parentheses, and a function invocation expression, which is getchar() with parentheses. Your code does not assign a function to a variable; it assigns the result produced by function invocation to variable c.

I thought a function only gets invoked when we invoke/call it, just like in test1.c

The difference between the two invocations, in test1.c vs. test2.c, is that test1.c invokes the function using a statement, while test2.c invokes the function using an expression. Both programs do invoke a function, though.

Upvotes: 4

Related Questions