Why typecast to void when call a function with no return value

S

su

I found in old code that when calling a void function:

void
foo() {
......
}
....
(void) foo();

I wonder why (void) is used to typecast the function.
Is there any historical reason?


Any reply from you will be appreciated.
 
I

Ian Collins

su said:
I found in old code that when calling a void function:

void
foo() {
.....
}
...
(void) foo();

I wonder why (void) is used to typecast the function.
Is there any historical reason?
"cast", actors get "typecast" :)

The reason is usually to suppress compiler or lint warnings, but they
tend not to be a problem with functions returning void.
 
S

su

Thanks. I got it.

Jack said:
There's no good reason at all to do this if foo() actually has a
"void" return type.

There are reasons for doing this is foo() actually returns a value of
some type. Some static code checking tools and coding standards
specify that the return value of every function should be checked or
specifically ignored.

So given:

int f(int arg);

...then:

f(12);

...violates the coding standard or generates a message from the code
checking tool, whereas:

(void)f(12);

...does not.

The first case could be the programmer making an error and forgetting
to check the return value.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html
 
C

CBFalconer

Jack said:
.... snip ...

.... snip ...

int f(int arg);

...then:

f(12);

...violates the coding standard or generates a message from the
code checking tool, whereas:

(void)f(12);

...does not.

The first case could be the programmer making an error and
forgetting to check the return value.

And the number of scanfs and similar calls one sees unchecked
indicate that insistance on the void usage might be helpful.
 

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,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top