473,725 Members | 2,197 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Return statement twice in the same expression

Hi, If i write:

#include <stdio.h>

int foo(int);

int main(void){
int a = 3;
foo(a);
}

int foo(int n){
n > 10 ? return 1 : return 0;
}

This code yields a compilation error, but if i write:

return n > 10 ? 1 : 0;

instead, it works. Why?
What does the standard say about that?

TIA

Nov 15 '05 #1
15 2805
"Nerox" <ne****@gmail.c om> writes:
int foo(int n){
n > 10 ? return 1 : return 0;
}


`return' is not an expression. It is a statement. You can't use
it that way.
--
"It wouldn't be a new C standard if it didn't give a
new meaning to the word `static'."
--Peter Seebach on C99
Nov 15 '05 #2
Nerox wrote:
Hi, If i write:

#include <stdio.h>

int foo(int);

int main(void){
int a = 3;
foo(a);
}

int foo(int n){
n > 10 ? return 1 : return 0;
}

This code yields a compilation error, but if i write:

return n > 10 ? 1 : 0;

instead, it works. Why?
What does the standard say about that?


The ternary operator (<expr1> ? <expr2> : <expr3>) is an operator, not
a control structure. [1]

All expressions involved in the ternary operator must yield a value.
The statement "Return x" does not yield a value, in fact it returns
control to the caller function, so there is no one to return a value
to. That's the reason why "n > 10 ? return 1 : return 0" gives
compilation errors.

return n > 10 ? 1 : 0, OTH is perfectly legal. The ternary operator
yields a value that is passed to return.

BTW, in your code it would be totally equivalent, and much cleaner to
simply write:

return n > 10;

[1] It can be used as a control structure. A sentence like:
n > 10 ? a = 1 : a = 0;
would be perfectly legal, but is bad practice. The reason why this is
legal is because an assigment does yield a value (the value being
assigned).

Nov 15 '05 #3
>int foo(int n){
n > 10 ? return 1 : return 0;
}

This code yields a compilation error, but if i write:

return n > 10 ? 1 : 0;

instead, it works. Why?
You cannot put *ANY* return statement in an expression.
You can, however, put an expression in a return statement.
What does the standard say about that?


A return statement is not an expression, therefore it can't be
mixed with ?: like you tried to in the first set of code above.

Gordon L. Burditt
Nov 15 '05 #4
All expressions involved in the ternary operator must yield a value.
The statement "Return x" does not yield a value, in fact it returns
control to the caller function, so there is no one to return a value
to. That's the reason why "n > 10 ? return 1 : return 0" gives
compilation errors.
int foo(int n){
n > 10 ? bar() : bar();

}

void bar(void)
{
printf("bar call\n");
}

Here, i think bar() doesn't return a value, however the code above
works.
I still don't understand it.
BTW, in your code it would be totally equivalent, and much cleaner to
simply write:


I know, this code is just an example in order to learn.

Thanks again.

Nov 15 '05 #5


Nerox wrote On 09/21/05 17:03,:
Hi, If i write:

#include <stdio.h>

int foo(int);

int main(void){
int a = 3;
foo(a);
}

int foo(int n){
n > 10 ? return 1 : return 0;
}

This code yields a compilation error, but if i write:

return n > 10 ? 1 : 0;

instead, it works. Why?
What does the standard say about that?


You have not understood the distinction between
"statements " and "expression s" in C. A "statement" can be
understood as an imperative: test a value with `if' and take
different execution paths depending on whether the value is
zero or not, repeat a section of code `while' a value is non-
zero, and so on. One of these imperatives is `return', which
tells C to cease executing the current function and resume
executing its caller, and may also pass a value back so the
caller can use it. The two forms of the imperative `return'
statement are

return;

return _expression_;

.... where the first form simply returns to the caller,
and the second also passes back the value of _expression_.
`n > 10 ? 1 : 0' is the _expression_ in your second
example, and "it works" because this is one of the two
permitted forms of the `return' statement.

An "expression " is a sequence of one or more operands
and zero or more operators, combined according to the
rules of the language. Expressions are not imperative in
the way statements are: they describe a computation that
produces a value, but say very little about how the value
is derived. For example, the expression `f(x) + g(y)'
produces a value that is the sum of `f(x)' and `g(y)', but
doesn't say whether to evaluate `f(x)' before or after
`g(y)'. It just describes the desired value and lets the
compiler figure out how to derive it.

So: can `return' be part of an expression? No, because
it is not an operand and it is not an operator: it makes
exactly as much sense as trying to put `for' or `goto' in
the middle of an expression, to wit, no sense at all. (Not
in C, anyhow; some languages do not distinguish so sharply
between expressions and statements). That's why your first
form yields a compilation error: you've written something
that looks a little bit like an expression, but contains
things that can't appear in expressions.

One source of confusion is that an expression plus a
semicolon can be used wherever a statement is permitted;
this usage is called an "expression statement." When you
see something like `x = 42;' it's tempting to think of it
as an "assignment statement," but it's really an expression
statement made from the expression `x = 42' and the `;'.
The expression happens to contain the assignment operator
`=', and the value produced by the expression (yes, it
produces one) is ignored, but it's really just an ordinary
expression, evaluated in order to achieve the side-effect
of storing a new value in `x'. Some other languages handle
assignment differently: original BASIC, for example, used
`LET X = 42'. In such languages the `=' or `:=' or whatever
is part of the punctuation of the assignment statement (the
way parentheses are part of the punctuation of `while'), but
in C the `=' is a full-fledged operator.

Here are a few more expression statements for you to
ponder -- if you think carefully, you'll realize that they
are all merely expressions and not imperatives, and that
they are all evaluated merely for their side-effects:

++i;

printf("Hello, world!\n");

p = malloc(sizeof *p);

free(p);

The fourth is different from the others in a subtle way.
The first three expressions all produce values that are
ignored: the value of the first is the new value given to
`i', that of the second is the number of characters written
(or EOF if there was an I/O error), that of the third is
the value assigned to `p'. But the fourth produces no value
at all. Some languages distinguish between "functions" that
return values and "subroutine s" that do not, but in C there
is no such distinction. Formally (and somewhat artificially)
speaking, the `free' function actually does declare the type
of value it returns -- but that type is `void', and the only
thing you can do with a `void' value is ignore it. This
vacuous `void' type lets C "regularize " itself, in a sense.
Instead of having parallel sets of rules for expressions that
do and don't produce values, C uses just one set of rules and
says that all expressions produce values -- but that some of
the produced values are `void'. (It's reminiscent of a legal
decision some years ago: the court held that an employer's
medical insurance plan did not discriminate against female
employees by failing to provide pregnancy benefits, because
the plan also denied pregnancy benefits to men and thus
treated both sexes equally.)

Summary: Although any expression can be turned into a
statement by appending a `;', no statement can appear as part
of an expression. An expression always produces a value (in
some cases a `void'), but a statement never produces a value
(not even a `void' one).

--
Er*********@sun .com

Nov 15 '05 #6
Nerox wrote:
All expressions involved in the ternary operator must yield a value.
The statement "Return x" does not yield a value, in fact it returns
control to the caller function, so there is no one to return a value
to. That's the reason why "n > 10 ? return 1 : return 0" gives
compilation errors.
int foo(int n){
n > 10 ? bar() : bar();

}

void bar(void)
{
printf("bar call\n");
}

Here, i think bar() doesn't return a value, however the code above
works.


Wrong, bar() does return a value. It returns an rvalue of type void.
It's tricky, but there is a subtle but all important difference.
I still don't understand it.
BTW, in your code it would be totally equivalent, and much cleaner to
simply write:


I know, this code is just an example in order to learn.

Thanks again.


You're wellcome.

Nov 15 '05 #7
"Nerox" <ne****@gmail.c om> writes:
All expressions involved in the ternary operator must yield a value.
The statement "Return x" does not yield a value, in fact it returns
control to the caller function, so there is no one to return a value
to. That's the reason why "n > 10 ? return 1 : return 0" gives
compilation errors.


int foo(int n){
n > 10 ? bar() : bar();

}

void bar(void)
{
printf("bar call\n");
}

Here, i think bar() doesn't return a value, however the code above
works.
I still don't understand it.


What do you mean when you say it "works"?

Things get a bit confusing when we talk about type void. An
expression can yield a result of type void, except that there are no
values of type void so it doesn't really yield a result at all. Sort
of.

The first operand of the "?:" operator must have scalar type
(something that can be compared to 0 to determine which of the other
two operands to evaluate). There are several legal possibilities for
the types of the second and third operands, one of which is that they
both have void type. The second and third operands' types have to be
closely related to each other, because the result of the whole
expression can be derived from either of them.

The second and third operands can't be return statements because a
return statement is not an expression (not even a void one); it's a
statement. Any expression can be used as a statement by adding a
semicolon, but statements in general cannot be used as expressions.

BTW, I know it's just an example, but you don't have a return
statement in your function foo().

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #8
Antonio Contreras wrote:
Nerox wrote:
int foo(int n){
n > 10 ? bar() : bar();
If there is no prototype of bar in scope, then bar will be presumed
to return an int on C90 implementations . Had you had the void bar(void)
prototype before your definition of foo(), then your compiler would
be required to issue a diagnostic (error/warning) for the constraint
violation.

BTW, foo() does not return a value here.
}

void bar(void)
{
printf("bar call\n");
}

Here, i think bar() doesn't return a value, however the code above
works.
Wrong, bar() does return a value.


No, it doesn't.
It returns an rvalue of type void.
It's tricky, but there is a subtle but all important difference.


You can prove anything from a false premice.

--
Peter

Nov 15 '05 #9
"Peter Nilsson" <ai***@acay.com .au> writes:
Antonio Contreras wrote:
Nerox wrote:
> int foo(int n){
> n > 10 ? bar() : bar();


If there is no prototype of bar in scope, then bar will be presumed
to return an int on C90 implementations . Had you had the void bar(void)
prototype before your definition of foo(), then your compiler would
be required to issue a diagnostic (error/warning) for the constraint
violation.


What constraint violation? C99 6.5.15p3 explicitly says that the
second and third operands of a '?:' operator may both have void type.

If he had written

return n > 10 ? bar() : bar();

or otherwise attempted to use the result of the expression, that would
have been a constraint violation.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #10

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

Similar topics

9
1633
by: Ximo | last post by:
Hello, I want that the return sentence don't return anything, how can I do it?. If i do only return it returns None, and pass don't run too. Can anyone help me?, thanks. XIMO
10
2612
by: LaEisem | last post by:
On-the-job, I have "inherited" a lot of old C language software. A question or two about when "casting" of null pointer constants is needed has occurred during behind-the-scenes cleanup of some of that software. That subject seems not to be addressed, at least not directly, in the C FAQ where FAQ 5.2 seems most relevant. References: * C FAQ 5.2 Null pointers (Including conditions where "casting" of null pointer...
7
585
by: Tobin Fricke | last post by:
I have a wrapper function I use to check the error conditions of various functions: wrap(foo(1,2,3)); (1) while (1 == wrap(bar("fluffy"))) { ... } (2) The wrapper function looks like this: int wrap(int code) { if (code) print_message(code);
15
6729
by: Greenhorn | last post by:
Hi, when a function doesn't specify a return type ,value what value is returned. In the below programme, the function sample()is returning the value passed to 'k'. sample(int); main() { int i = 0,j; j = sample(0);
3
6345
by: LP | last post by:
Hi, Considering the following code: using(mySQLconn) { if (someCondition==true) return 0; //more code after return //do some db calls
2
11714
by: Raj | last post by:
Hi, I was getting an error in my program saying that return keyword must not be followed by an object expression. I was confused first because I was using return statement in a valid "if" statement. e.g. if(expression) return false; Later, I found that this error was due to a mistake in my method declaration. I had put void as a return type in my method. When I changed this to bool, everything works.
66
3624
by: Johan Tibell | last post by:
I've written a piece of code that uses sockets a lot (I know that sockets aren't portable C, this is not a question about sockets per se). Much of my code ended up looking like this: if (function(socket, args) == -1) { perror("function"); exit(EXIT_FAILURE); } I feel that the ifs destroy the readability of my code. Would it be
51
3946
by: James Harris | last post by:
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
6
1830
by: exander77 | last post by:
I am quite new to c++, about half of a year. I juct wonder, why such code is not possible: int chlen(char * ar) { for(int i=0;ar||return i;i++); } In my opinion, it would be much "cuter" than this: int chlen(char * ar) {
0
8752
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
9257
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9176
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9113
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8097
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
6702
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
4519
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3221
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
2635
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.