Showing posts with label C++. Show all posts
Showing posts with label C++. Show all posts

Friday, February 27, 2009

Subroutine Pointer in C

C has subroutine pointers. It does not require closures because it does not have nested scopes and it is static scoped. Every subroutine is at global scope. As a result, the referencing environment for a subroutine is the same whether it is created when the subroutine is first passed a parameter or when the subroutine is finally called. In the following code, plus_one has the same referencing environment whether the referencing environment is created when it is passed as a parameter to caller or when it is called in caller.

#include
int plus_one(int n) {
return n + 1;
}
void caller(int (*f) (int)) {
int result = f(3);
printf("3 plus 1 is %d\n", result);
}
int main() {
caller(plus_one);
return 0;
}

For a language which supports nested scope, the situation is different. In the following Common Lisp code, a closure must be created for plus_2 to make it a function which addes 2 to its sole parameter.

(let ((one 1))
(defun plus_1 (x)
(+ x one)))

(let ((one 5))
(plus_1 3))

Thursday, June 12, 2008

variable type checking in C

Put all the files in a directory. Run gcc *.c -o main.exe. The compilation will succeed. The reason is that C does not check type consistency of external variable declaration and reference.
1 one.c

int abc = 1;

2 main.c

#include <stdio.h>
extern float abc;
int main(void) {
printf( "%f", abc );
}

Function type checking in C

Put all the following 3 files in a directory. Run gcc *.c. The compilation will succeed. And running the resulted excecutable file will print I am here, man!. Run g++ *.c The compilation will fail. The reason is that during linking, C only check function names. But C++ check function type.
1. caller.c

#include "callee.h"
int main(void) {
foo();
}

2. callee.h

int foo(void);

3. callee.c

#include
void foo(int v) {
printf( "I am here, man!" );
}