473,769 Members | 1,640 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C return a++ - is it safe?

If in C one codes a function which includes

return a++;

does 'a' get incremented? Would the behaviour be safe to rely upon? I
guess this might apply if 'a' were static or such as

return ptr->element++;

I didn't find this in the comp.lang.c faq (at least the first one that
came up from Google; there seemed to be many) but didn't find it. No
doubt someone will tell me where I should have looked.

(For the time being I'm coding: a++; return a - 1; )
--
James

Oct 29 '07
51 3968
Chris Hills wrote:

[...]
Regardless of the standard(s) I think this is one you would need to
empirically test of the compiler(s) in question.

If this were Ada one could just refer to the standard but it's C and
nothing is guaranteed.
Well, some C compilers has been validated:

http://www.peren.com/pages/cvsa_set.htm
http://www.plumhall.com/stec.html

and at this point, the C90 test cases should detect such an compiler
bug. However, in safety-critical SW, I wouldn't advocate using construct
like

return a++;

anyway.

--
Tor <bw****@wvtqvm. vw | tr i-za-h a-z>
Oct 30 '07 #11
On 30 Oct, 20:10, Keith Thompson <ks...@mib.orgw rote:
....
Consider how the return statement is defined: the expression is
evaluated, and the result is returned. Updating ``a'' is part of the
evaluation of the expression.

Is there some particular reason you're concerned that a compiler might
handle something this simple incorrectly?
In any context other than a return statement
mov eax, a
{use eax}
inc eax

So in a return statement
mov eax, a
ret
inc eax

which, of course, is wrong so the compiler should handle two special
cases:

1. return a++; where a is automatic
mov eax, a
ret
/* ignore the ++ */

2. return a++; where a persists
mov eax, a
mov ebx, eax
inc ebx
mov a, ebx
ret

Oct 30 '07 #12
In article <ln************ @nuthaus.mib.or gKeith Thompson <ks***@mib.orgw rites:
....
All software (including compilers) has bugs. All software should be
thoroughly tested. But a compiler bug in the handling of ``return
a++;'' is quite low on the list of things I'd worry about -- higher
than ``1 + 1 == 2'', lower than, say, some obscure C99 feature, and
about the same as ``return (a = 42);''.
You would be surprised at the bugs I have seen in compilers and
assemblers. It ranges from blatant errors in something akin to
include files (wrong values all over the place for floating point
attributes in the DG Ada compiler) to issuing the wrong opcode
for a particular inxtruction (a Gould assembler).
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
Oct 31 '07 #13
Tor Rustad wrote:
Chris Hills wrote:

[...]
>Regardless of the standard(s) I think this is one you would need to
empirically test of the compiler(s) in question.

If this were Ada one could just refer to the standard but it's C and
nothing is guaranteed.

Well, some C compilers has been validated:

http://www.peren.com/pages/cvsa_set.htm
http://www.plumhall.com/stec.html

and at this point, the C90 test cases should detect such an compiler
bug. However, in safety-critical SW, I wouldn't advocate using construct
like

return a++;
I'm sorry - but if you have a compiler you can't trust to handle 'return
a++;' correctly, why are you using it, even for software that isn't
safety critical (and especially for code that is)? If there's any
significant likelihood that it might mishandle something that simple, I
most certainly wouldn't want to write anything more complicated in it.
Oct 31 '07 #14
On Oct 31, 4:22 am, James Harris <james.harri... @googlemail.com >
wrote:
On 30 Oct, 20:10, Keith Thompson <ks...@mib.orgw rote:
...
Consider how the return statement is defined: the expression is
evaluated, and the result is returned. Updating ``a'' is part of the
evaluation of the expression.
The above answers the query :):)
So, return statement has defined that the expression is evaluated and
the
result is returned. :):)
>
Is there some particular reason you're concerned that a compiler might
handle something this simple incorrectly?

In any context other than a return statement
mov eax, a
{use eax}
inc eax

So in a return statement
mov eax, a
ret
inc eax

which, of course, is wrong so the compiler should handle two special
cases:

1. return a++; where a is automatic
mov eax, a
ret
/* ignore the ++ */

2. return a++; where a persists
mov eax, a
mov ebx, eax
inc ebx
mov a, ebx
ret
Interesting :):)

Karthik Balaguru

Oct 31 '07 #15
[... Talking about "return a++;" ...]

Martin Wells wrote:
>
Kenneth:
However, if "a" were a non-static non-volatile automatic variable,
can the compiler skip the increment? I believe so, because it will
go out of scope upon executing the return, and the result is "as
if" the increment were actually done.

If the local variable were neither volatile nor static, then the
increment is utterly redundant... and I wouldn't mind the compiler
issuing a warning something like:

WARNING: Redundant operation on local automatic variable
"Redundant" , or "useless"?
Only two reasons come to mind as to why you'd have a redundant
operation on a local automatic variable:

1) You intended to define it as either static or volatile.
2) You're stupid.
3) You're wondering whether your compiler will optimize it away.

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer .h|
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>
Oct 31 '07 #16
Tor Rustad wrote On 10/30/07 19:06,:
[...]
However, in safety-critical SW, I wouldn't advocate using construct
like

return a++;
What's your opinion of `return getchar();'? Keep
in mind that in many implementations , getchar() is a
macro that expands to an expression with side-effects.
On an implementation I happen to have handy at the
moment, `return getchar();' produces (reformatted for
clarity)

return ( --(( &__iob[0]))->_cnt < 0
? __filbuf( (&__iob[0]) )
: (int) *(( &__iob[0]))->_ptr++ );

So, what's your verdict? Should `return getchar();'
be avoided in safety-critical software?

--
Er*********@sun .com
Oct 31 '07 #17
On Oct 30, 11:35 am, Chris Hills <ch...@phaedsys .orgwrote:
In article <47274b17.15255 6...@news.sbtc. net>, Richard Harter
<c...@tiac.netw rites
[...]
>
I believe you're missing his point. Ada has a very thorough
validation suite and stringent restrictions on what may be called
an Ada compiler. This isn't the case with C compilers; anybody
can produce what they call a C compiler. It is even possible
that there is no such thing as a fully conforming C compiler.
His point is that in the real world this is the kind of thing
that you should check whether the compiler gets it right.

Precisely
Off
hand, I would think that it is the sort of thing that a compiler
could be expected to get right but I might well be wrong.

In other words you wouldn't bet your life on it....
In that case (betting my life), Ada has no advantage over C.

"Trust, but verify."

Regards,

-=Dave

Oct 31 '07 #18
Kenneth Brody wrote:

[in addition, my response applies to Kuyper and Sosman]
Tor Rustad wrote:
[...]
>However, in safety-critical SW, I wouldn't advocate using construct
like

return a++;

anyway.

Why not? If the compiler doesn't handle it right, then I wouldn't
trust it for the rest of the "safety-critical" program either.

First, I didn't agree with Chris Hills, because

1. I didn't find such a C compiler bug likely
2. If such a compiler bug existed, the unit test should detect it

My comment on not advocating returning a++, is more of a stylish matter,
since post conditions in functions, usually follow after the last
expression, and before the return statement.

Returning expressions, obfuscate debugging too.

--
Tor <bw****@wvtqvm. vw | tr i-za-h a-z>
Oct 31 '07 #19
On Wed, 31 Oct 2007 02:50:41 GMT, in comp.lang.c , James Kuyper
<ja*********@ve rizon.netwrote:
>Tor Rustad wrote:
>However, in safety-critical SW, I wouldn't advocate using construct
like

return a++;

I'm sorry - but if you have a compiler you can't trust to handle 'return
a++;'
AFAICS, its not a question of whether the /compiler/ can handle it,
its a question of whether the programmers understand what it does. See
for instance this entire thread.

--
Mark McIntyre

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Oct 31 '07 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
10494
by: John Eskie | last post by:
Hello, I've seen in some programs that they provide functions which has the following prototype: char *func1(); However I'm not sure it's safe. If the char array beeing returned is a local variable such as: char *func1()
1
2621
by: Tropos | last post by:
Query: Will a MutexGuard object release before a function return value is copied? Consider the C++ code: class MutexGuard //A familiar sort of class for making mutexes exception-safe { . . . ~MutexGuard(); //releases the mutex when the stack pops
7
3576
by: Sims | last post by:
Hi, if i have a code const char * GetValue() { std::string szVectorValue = ...// get a std::string from the vector return szVectorValue.c_str(); }
5
4338
by: starket | last post by:
Hi folks, I'm new to programming, please help, char * b, q, *r; b=getbuf(); q = *b; r= anotherfunction(b); /* we want to use ‘q' and ‘r' here*/ char * getbuf() {
2
2631
by: Neil Schemenauer | last post by:
python-dev@python.org.] The PEP has been rewritten based on a suggestion by Guido to change str() rather than adding a new built-in function. Based on my testing, I believe the idea is feasible. It would be helpful if people could test the patched Python with their own applications and report any incompatibilities. PEP: 349
7
6146
by: Jim Showalter | last post by:
I always thought that it is safe for a function to return a pointer to static storage. And the following code does compile quietly with: gcc -pedantic -Wall -o foo foo.c #include <stdio.h> static char *foo (int y) { static char s;
14
3717
by: zeroDontSpamtype | last post by:
Hi, Why do strcpy and strcat (and strupr and strlwr in some nonstandard implementations) return a char*? Surely the logical (and DMA-safe) )return type for these would have been void?? Thanks, James McLaughlin.
13
2914
by: cppquester | last post by:
A colleague told me that there is a rule about good stype that a function in C++ should have only one point of return (ie. return statement). Otherwise there might be trouble. I never heard about it and doubt it. Anybody heard of it? What would be the advantage? Regards, Marc Example:
173
8179
by: Marty James | last post by:
Howdy, I was reflecting recently on malloc. Obviously, for tiny allocations like 20 bytes to strcpy a filename or something, there's no point putting in a check on the return value of malloc. OTOH, if you're allocating a gigabyte for a large array, this might fail, so you should definitely check for a NULL return.
50
5237
by: Bill Cunningham | last post by:
I have just read atoi() returns no errors. It returns an int though and the value of the int is supposed to be the value of the conversion. It seems to me that right there tells you if there was success or not. Am I wrong? Bill
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10211
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8870
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7408
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6673
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3958
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3561
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.