Calling C function in C++ without deafult arguments

P

pkpatil

Hi,

I recently saw a code with a mix of C & C++, wherein a C++ file was
calling a C function dropping the last argument. The code was similar
to below:
--------------------------------------------------------------------------------------------------------------
cfile.c
---------
C_Fun(int arg1, int arg2, int arg3) { // C function with three
parameters
}

cppfile.cpp
----------------
extern "C" { C_Fun(int arg1, int arg2); } //Note: declaring the C
function as taking only two parameters

OtherFunction() {
int first, int second;
C_Fun(first, second) //Note: passing only two parameters
}
--------------------------------------------------------------------------------------------------------------

This code did get built when linked together (using gcc), but how is
this allowed? Is the last argument to C function, "arg3" treated as
default argument with value of zero as
"C_Fun(int arg1, int arg2, int arg3=0);" ?

Thanks,
PK
 
A

Artie Gold

Hi,

I recently saw a code with a mix of C & C++, wherein a C++ file was
calling a C function dropping the last argument. The code was similar
to below:
--------------------------------------------------------------------------------------------------------------
cfile.c
---------
C_Fun(int arg1, int arg2, int arg3) { // C function with three
parameters
}

cppfile.cpp
----------------
extern "C" { C_Fun(int arg1, int arg2); } //Note: declaring the C
function as taking only two parameters

OtherFunction() {
int first, int second;
C_Fun(first, second) //Note: passing only two parameters
}
--------------------------------------------------------------------------------------------------------------

This code did get built when linked together (using gcc), but how is
this allowed? Is the last argument to C function, "arg3" treated as
default argument with value of zero as
"C_Fun(int arg1, int arg2, int arg3=0);" ?

Thanks,
PK

It's undefined behavior. Whoever wrote the code lied. From a language
perspective, anything, including nasal demons[1] may ensue.

A further perspective is that C++ linkage encodes the number and types
of parameters in the mangled name that the linker sees, and is hence
more type safe; C (and hence "C" linkage in C++) does no such thing --
allowing one to (as in this case) shoot oneself in the foot. Or worse.

HTH,
--ag

[1] Google for it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,734
Messages
2,569,441
Members
44,832
Latest member
GlennSmall

Latest Threads

Top