What is this kind of coding style in c? - c

(void) fputs( line, stdout );
(void) alarm( TIMEOUT );
The above appears in the function body,I've never seen such code before...

It's a form of coding to debugging tools at the expense of human beings reading your code, and it's Considered Harmful. In particular, the classic lint tool and perhaps some compilers generated warnings if you did not use the return value of a function that returned a value, and the only way to suppress this locally was to cast the result to void.
Either ignore it, or fix it (remove the useless void casts) if you have sufficient authority to do so.

The only thing unusual are the casts to void. It's a way to indicate that you're going to ignore the return value of the function, or to indicate that a function returns no value. Some compilers warn about ignored return values, so can be a way around that warning. I don't think it's very good style myself.

If you mean the (void) part, then that is explicitly discarding the result of the function call. fputs(...) returns an int. (void) fputs(...) discards the int return value without generating compiler warnings.

Related

Why does C let you ignore returned values from functions?

Let's say I have the following C code:
int return_one()
{
return 1;
}
int main(void)
{
return_one();
}
Within the main function, I call function return_one() and ignore the return value. The compiler has no issue with me ignoring this value.
What is the logic as to why this okay? Was it an arbitrary design choice from the C creators? Or is there a practical reason for not requiring the calling function to use the return value?
I think the main reason is the usual one — history.
Before the C standard, there was no option to use void to indicate 'no return value'. Functions returned an int unless you specified that they returned some other type, but that other type couldn't be void (it didn't exist). So functions for which the return value was immaterial didn't return a value — even though the function was implicitly returning type int. (Usually, the return type was omitted — the function was implicitly returning an int.) You got UB if the calling code tried to use a value but the called function didn't return a value.
All this meant that it was commonplace to ignore the return value of functions — especially functions that nominally returned an int but actually didn't return any value. There wasn't a better way of dealing with it. Nowadays, with void return types, there are better ways to deal with it. Nevertheless, it remains true that the return value is often of limited interest. How often do you check the return value of printf() or one of its friends? How often do you use the return value of strcpy() et al?
C90 had to allow old code to run still, so it allowed the old, pre-standard behaviour. C99 tightened the rules — functions were no longer implicitly of type int and had to be declared (with an explicit return type, possibly void) before they could be used.
Because people don't care about a lot of return values, so why force them to use them?
A ton of standard C functions return values that are essentially never looked at. Think about all the C code you've ever looked at. Have you ever seen someone do anything with the return value from the printf family of functions? Because they all have one, but you'd never know it to look at real world code. Would it be improved if every single call to printf had to prefix it with an explicit "I don't care about the return value" bit of syntax (e.g. (void)), because 99.99% of the time, you don't actually care how many bytes you printed, but printf computes and returns it anyway? Basically, you're allowed to not use the return value because there's was no need to force you to do so, and it's often not needed.
tl;dr: You can write code such that the return values are always relevant - in that case ignoring them would be a bug. However, some (particularly older) code does not work that way, there ignoring return values may be reasonable.
What is the logic as to why this okay? Was it an arbitrary design
choice from the C creators?
It is not just a choice by the C creators, many other languages also allow this - as a matter of fact, I cannot think of a language where ignoring the return value is considered an error.
The practical motivation for this is mainly that the return value of a function is often used for reporting errors, or reporting details of what the function did. Sometimes, you are not interested in these details, so you ignore them. A common example of this is the C function printf, which returns the number of characters printed. While this may sometimes be useful, it is usually not, so the return value of printf is usually ignored.
This is arguably a bad design (either in your code, or in the function that returns stuff noone wants), but it is established practice, so C (like other languages) supports this.
Or is there a practical reason for not requiring the calling function to use the return value?
No, there is no practical reason for ignoring return values - unless you do not want them.
While the above is the historical practice, many people now consider ignoring return values a problem (or a symptom of a deeper problem):
If the return value is for error reporting, ignoring it will work usually, but cause problems if there really is an error. This is now usually considered a bad idea.
Generally, if you can ignore the return value, that means the function is causing side-effects (otherwise calling it would be pointless). Many people think that it is better to have functions only do one thing - either cause a side effect (and return nothing), or return a value (and have no side effects). The latter is often called a pure function (with the additional condition of the output only depending on the input). This separation makes it easier to understand software - and if you use it, ignoring a return value is necessarily a mistake, because functions returning a result do nothing else, so if you ignore the result, calling it is pointless.
So in other words: If you follow certain conventions, there should be no situation where you want to ignore return values, in that case ignoring them is usually a mistake. Without these conventions, there may be good reasons for ignoring them, so there's no general rule.

Ambiguity of return values

In the C language book (by K&R), in the section on low level I/O , I came across two functions read() and close() both of which have an integer return type. But I have seen that they are being used without even caring to assign the return value to any integer variable. But when I create a user defined function having integer return type and use it without assigning it to integer variable it causes compiler warning. Why this inconsistency?
Compilers traditionally don't warn for omitting the result of library function calls. Functions like printf, scanf and memcpy do return something, yet someone back in the dark ages of K&R decided to implicitly skip checking the result of the functions. It became de facto standard. Although to this day, skipping the result remains bad practice in many cases (like in the case of scanf).
Compilers do warn if you don't check the result of application functions though, because that's almost always a bug. If you deliberately don't want to check the result, you should write (void) func(); to silence such warnings.
(Side note: read and close aren't standard C, but Unix API. Still they are library functions.)

Why does the standard let functions that don't return compile?

f() does not return even though it's signature say it should.
Why is the reason for allowing this to compiling?
Is there a reason the C standard does not require the compiler to make it fail?
I know that it is Undefined behavior and all, but why is it allowed in the first place?
Is there a historical reason?
double f(){}
int main()
{
f();
return 0;
}
Is there a reason the C standard does not require the compiler to make
it fail?
By invoking undefined behavior, the C standard allowed the compilers to be less complicated. There is indeed some cases, such as if statements, in which it is hard to say whether the function returns a value or not:
int f(int n)
{
if (n > 0) return 1;
}
If I write f(5), it is easy for the compiler to say that the
function is correct.
If I write f(-5), it is also easy to detect
an undefined return value.
But if the argument comes from user input for example, how should the compiler be able to know whether the function returns a value? Since this could both a valid or a wrong program, C standard allows the compilers to do what they want. C is designed to be as smart and simple as possible.
The compiler could certainly analyze all code paths for the function and reject the program if it cannot prove that the function always returns a meaningful value. I suppose the reason the standard does not mandate it is that in the old days compilers were much less sophisticated than we work with today.
Of course using the return value of such a function is undefined behavior:
If the } that terminates a function is reached, and the value of the
function call is used by the caller, the behavior is undefined.
It's easy to tell that your function will reach the end without returning a value. It doesn't return and it doesn't call any code that could prevent it reaching the end (like abort()).
In fact your program does not have undefined behavior in C99, since the missing return value isn't used by the caller. 6.9.1/12:
If the } that terminates a function is reached, and the value of the
function call is used by the caller, the behavior is undefined.
So your code has questionable style, but is well-defined.
The C++ standard changes the rule and remarks on that change in [diff.stat]. It says that the C version of the rule is to support code that was written back in the days when C didn't distinguish between int return and void return. So the reason your code has defined behavior in the first place is "legacy". That said, AFAIK C has always distinguished between double return and int return, so it could probably have made it UB for a function returning double to fall off the end, had it been done at the right time.
Leaving aside whether the return value is used, consider a tricker function:
double f() {
if (g()) exit();
}
This function also contains no return statements, but doesn't reach the end of the function if in fact g always returns a true value or doesn't return at all. So this function should be accepted even if its return value is used, on the general C standard principle that you're expected to know what you're doing and mean what you say. If g is defined in a different TU then you probably know more about it than the compiler does.
Even if it weren't for the legacy reasons, I'm pretty sure that the standard simply cannot be bothered adding text in order to define what non-return scenarios compilers are required to detect. It's left to quality of implementation -- if it can be determined at compile time that your function cannot possibly avoid UB then maybe the compiler will warn anyway despite no diagnostic being required. For that matter, it will occasionally warn when behavior is defined on the general C implementer's principle that some things are so daft that no user could reasonably mean them.
Because the compiler can not tell if the function returns at runtime or not.

Unknown C expression

I ran across the following line in an example program, and don't know what it is. I imagine it's a function call, but am not sure:
(void) pthread_mutex_init(&bottleneck, &mxattr);
If it is a function call, why is it preceded with (void)? I've never seen that before. Here's the line in more context:
attr_init(pthread_process, pthread_scope, stacksize);
(void) pthread_mutex_init(&bottleneck, &mxattr);
barrier_init(&setup_barrier, (2 * ntables) + 1);
Thanks for the help. The entire program is from this Solaris whitepaper (Appendix D)
It is a normal function call. The (void) part just indicates that the function returns a value and nothing will be done with it. To remove any warnings of about unused return values.
See casting unused return values to void.
POSIX Threads
The specific call - pthread_mutex_init - returns int. The cast to void is probably done to avoid specific warning about the return value being ignored during either compile time or a static code analysis.
Update: As #Jack Kelly commented on another answer, any good static analysis tool would simply ignore this cast and continue issuing the warning. Static analysis should be controlled through separate specific annotations, not by using language constructs that can affect the compiler output.
This is a function call with explicit casting of the result to void. This is just a development style to hint both compiler and those who read this code that function call is actually returning something that is intentionally ignored. In this example, pthread_mutex_init function returns integer. Some compilers will give you a warning if you call a function marked with warn_unused_result attribute.
Yes it is a function call. The function pthread_mutex_init() initializes a mutex used to prevent multiple threads clobberring some shared resource.
The function returns an int, the (void) is flagging that we are intentionally ignoring the return value. It stops the compiler complaining about unused return values.

Need for prefixing a function with (void)

I recently came across a rather unusual coding convention wherein the call for a function returning "void" is prefixed with (void).
e.g.
(void) MyFunction();
Is it any different from the function call like:
MyFunction();
Has it got any advantage or is it yet another needless but there coding convention of some sort?
Some functions like printf() return a value that is almost never used in real code (in the case of printf, the number of characters printed). However, some tools, like lint, expect that if a function returns a value it must be used, and will complain unless you write something like:
int n = printf( "hello" );
using the void cast:
(void) printf( "hello" );
is a way of telling such tools you really don't want to use the return value, thus keeping them quiet. If you don't use such tools, you don't need to bother, and in any case most tools allow you to configure them to ignore return values from specific functions.
No, there isn't any difference -- what's being cast to void is the return value of the function.
I'd say it could make sense of you wanted to make explicit you're not using the return value (you're calling it for the side effects), but as the function already has void return, it doesn't make much sense.
If the function returns something the void could avoid (!) a warning (indeed in no way I was able to make gcc warn me that the return value is lost) on some compilers (or lint tools); but more importantly, it makes clear that a return value is "thrown" away purposely (and not by mistake).
acedemically: a "function" always returns something, else it would be a procedure. So the Author of this code wants to say "i know this naming is wrong, but i will no change the name, so i make this disturbance visible"
Has it got any advantage or is it yet another needless but there coding convention of some sort?
No difference. It is a quite common convention e.g. in software testing to highlight the fact that in context the function return, if any, is safe to be discarded.
In HPUX man pages it is quite common in example code to see a cast to void to get around lint warnings.
fprintf(mystream, "%s\n", "foo");
vs.
(void)fprintf(mystream, "%s\n", "foo");
That may be where the author of the code is coming from. IMO, this is not a great idea because most of the sprintf family, for example, call malloc. malloc will fail when there is not enough memory. SIGINT also causes the underlying write() syscall to interrupt and not write all of the buffer, for printf() family members.

Resources