Destructors in C

A

alex.gman

If I have code like this

int f() {
// ... stuff ...
g();
if(x > 0) return (x+4);
// ... more stuff ...
always_call(z);
return y;
}

can I insure that always_call will be called even when the conditional
(x > 0) succeeds and when g() might contain non-local jumps?

I'm basically curious what C++-hating hard-core C programmers use to
achieve what C++ destructors give you. The common opinion is that their
choices are not good.
 
I

Ico

int f() {
// ... stuff ...
g();
if(x > 0) return (x+4);
// ... more stuff ...
always_call(z);
return y;
}

can I insure that always_call will be called even when the conditional
(x > 0) succeeds and when g() might contain non-local jumps?

I do not really understand what you want to achieve here; You choose to
return from the function prematurely, but still you want the code
*after* the return to execute. To my knowledge, this is not what
destructors are about.

Having more then one return in a function is considered bad practice by
some, because it obfuscates program flow.

I'm basically curious what C++-hating hard-core C programmers use to
achieve what C++ destructors give you. The common opinion is that their
choices are not good.

I do a lot of object-oriented programming with C. My 'object' usually is
a pointer to a struct of a specific type. I create a function new()
which allocates, initializes and returns a pointer to this type. I
create function del() which 'destructs' and frees the object. As far as
I know, this is similar to C++ constructors and destructors.

I do not think you gave good example for talking about destructors.
Destructors are not 'pieces of code that run after you have returned
from a function'.

Ico
 
O

olaf.giezenaar

This is not true

After a return statement no code is executed it the function

So don't post these silly things.


Greetings Olaf
 
C

Chris Dollin

This is not true

/What/ is not true?
After a return statement no code is executed it the function

So don't post these silly things.

You might try and understand what the OP is asking before you
brush them off like that.

The OP asked:

The answer is that, no, in C you can't do that, except by doing it
all "by hand"; you must be able to trap any non-local jumps out of
g (which you have to do with the connivance of g and everything it
calls that might longjump) and you have to arrange that always-call
is executed before every return. In C++ the compiler handles this
for destructor code; in C you have to /be/ that compiler (without
the advantage of having total control over the generated code).
 

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

No members online now.

Forum statistics

Threads
474,172
Messages
2,570,934
Members
47,477
Latest member
ColumbusMa

Latest Threads

Top