Can we use break statement in conditional operator?

J

jayapal

Hi

the scenario is like this:

func()
{
....
....

char *p= (char *)&str[0];
while (p)
*++p=='$' ? break:(*p != ' ' ? return error : )
.....
.....

}

can i use conditional operator like these
 
J

James Kuyper

jayapal said:
Hi

the scenario is like this:

func()
{
...
...

char *p= (char *)&str[0];
while (p)
*++p=='$' ? break:(*p != ' ' ? return error : )

No. the second operand in a conditional-expression is required to be an
expression. 'break;' and 'return error;' are statements, not an expressions.
 
V

vipvipvipvipvip.ru

Notice if str[] = "$" your func() will.. 'fail'.
Also, you want while(*p) and not while(p).
Also, if str is of type char * or char[], the cast is not needed.
&str[0] is a char *.

int func(const char * str) {

while(!isspace(*str))
if(*str == '$') break;

return *str == '$';
}
 
V

vipvipvipvipvip.ru

On Oct 30, 2:11 pm, (e-mail address removed) wrote:> while(!isspace(*str))

sorry, while(*str && !isspace(*str))

Damn, i don't increment str in the loop.
Sorry for this; it's been a long day
 
C

Chris Dollin

jayapal said:
Hi

the scenario is like this:

func()
{
...
...

char *p= (char *)&str[0];
while (p)
*++p=='$' ? break:(*p != ' ' ? return error : )
....
....

}

can i use conditional operator like these

As at least one other person has said, no. And even if you /could/,
you couldn't write what you wrote, because there's nothing after
the second `:`. And even if you could do /that/, what exactly is
this loop supposed to accomplish? It /looks/ like (fx:emulate) it
skips the first character [if any] and then skips spaces and
either returns the error value if it's not at $-or-eos, or
falls through pointing at $-or-eos.

If so, I would have thought:

char *p = str; /* suspect the casting and indexing useless */

if (*p) p += 1;
while (*p == ' ') p += 1;

if (*p == '$') { whatever } else return error;

was more transparent. (I have a stylistic preference away from using
++ when the result isn't consumed; feel free to replace `p += 1` by
`p++` in the above if you have the reverse preference.)
 
C

Chris Dollin

Notice if str[] = "$" your func() will.. 'fail'.
Also, you want while(*p) and not while(p).
Also, if str is of type char * or char[], the cast is not needed.
&str[0] is a char *.

int func(const char * str) {

while(!isspace(*str))
if(*str == '$') break;

return *str == '$';

We don't know that `func` returns `*str == '$'`, since the OP didn't
provide the remainder of its body after the loop.
 

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,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top