How can we code conditional behavior without using if or ? (ternary operator) ?
One idea comes to mind:
for(;boolean_expression;) {
// our code
break;
}
Any others ?
I hope what you dont want is just 'if' or 'ternary'.
#1
How about this:
Instead of : if (condition) printf("Hi");
Use:
condition && printf("Hi");
Short circuit evaluation. This is much similar to using if though.
#2
For if (condition) a(); else b();
Use:
int (*p[2])(void) = {b, a};
(p[!!condition])()
Using array of function pointers, and double negation.
#3
Yet another variant close to ternary operator (function, though)
ternary_fn(int cond, int trueVal, int falseVal){
int arr[2];
arr[!!cond] = falseVal;
arr[!cond] = trueVal;
return arr[0];
}
Use it like ret = ternary_fn(a>b, 5, 3) instead of ret = a > b ? 5 : 3;
switch(condition){
case TRUE:
ourcode();
break;
default:
somethingelse();
}
Using function pointers:
void ourcode(void){puts("Yes!");}
void somethingelse(void){puts("No!");}
void (*_if[])(void) = { somethingelse,ourcode };
int main(void){
_if[1==1]();
_if[1==0]();
return 0;
}
This relies on true boolean expressions evaluating to 1, which happens to be true for gcc, but I don't think it is guaranteed by the standard.
Related
I wanted to do unit tests for the functions in my game.
In this case, I did the first test to see if the result is true but I don't seem to find a solution if the result is false
void test_pion_available(void)
{
int a;
a = pion_available();
TEST_ASSERT_EQUAL_INT(1, a);
/* miss the test if the result is false */
}
There may be some better way in you testing framework (like TEST_ASSERT_FALSE(a);?), but at least values other than 0 means true and 0 means false in C, so you can check if the result is 0 to check if the result is false.
void test_pion_not_available(void)
{
int a;
a = pion_available();
TEST_ASSERT_EQUAL_INT(0, a);
}
after some reseachers i found this:
void test_pion_not_available(void)
{
int a;
a = pion_available();
TEST_ASSERT_EQUAL_INT(1, a); // or TEST_ASSERT(a == 1)
// test if the result is false
TEST_ASSERT_FALSE(a != 1); //Evaluates whatever code is in condition and fails if it evaluates to true
}
Is the following idea possible in C?
I am reaching failed. (using online c compiler to test this)
Maybe it is solvable using GOTO, but that is not desired.
Just theoretical, if there is any other solution i am missing, but the idea is to have a statemachine just be a little bit more efficient.
#include <stdio.h>
#include <stdint.h>
uint8_t shouldhavebreaked = 0;
#define BREAK_CONDITIONAL(x,y) do { if(x == y) { shouldhavebreaked = 1; break ;} } while(0)
int main()
{
uint8_t swh = 0;
switch (swh)
{
case 0:
/*if state is same, break, otherwise fall-through*/
BREAK_CONDITIONAL(swh, 0);
case 1:
printf("failed \n");
break;
}
printf("changed? %d \n",shouldhavebreaked);
return 0;
}
Instead of the funky do{}while() you could use the less funky if(){} else:
#define BREAK_CONDITIONAL(x,y) if(x == y) { shouldhavebreaked = 1; break; } else
And it is a good habit to over-parenthesize arguments in macros:
#define BREAK_CONDITIONAL(x,y) if((x)==(y)) { shouldhavebreaked=1;break;} else
Those kinds of macros do not make any sense (unless you want to make code more difficult to read, understand and maintain. It will be more error-prone as well). Avoid as a plague. They look like functions and they are not.
If I hide the macro from the #wildplasser answer can you guess what this nonsense does?
if(c)
{
BREAK_CONDITIONAL(a,b) c = a+b;
}
For those of you who didn't understand - I KNOW this is NOT how a good code should look like... The purpose of this tricky question is to write a code without if-statements in order to practice boolean logic...
I'm trying to solve a question in C which restricts the programmer from using if/else/switch statements. cant use ternary operators either.
The idea is to use boolean based logical statements to get the "wanted path".
i.e - instead of:
if (1 > 0)
printf("TRUE")
else
printf("FALSE")
I would use:
bool res = true;
res = (1 > 0 && printf("TRUE")) || printf("FALSE")
(this is the general idea, using the boolean statement processing logic to manipulate different actions.
The only problem I ran into was to replace a part that looks somewhat like this (where i want the program to skip a certain part of the loop if A is equal to B):
while (...)
{
if (A == B)
continue;
//code
}
Do you know if this is possible to execute without using if/else/switch statements?
Thanks!!
The equivalent of your
while (condition)
{
foo();
if (A == B)
continue;
bar();
baz();
}
is
while (condition)
{
foo();
(A != B) && bar();
(A != B) && baz();
}
This assumes bar() doesn't change A or B. If it does, use a temporary variable:
while (condition)
{
foo();
bool cond = A != B;
cond && bar();
cond && baz();
}
Do you know if this is possible to execute without using if/else/switch statements?
With gcc extension statement expressions you can do this:
int main() {
int A, B;
while (1) {
A == B && ({continue;0;});
}
}
Please don't do this and please don't do res = (1 > 0 && printf("TRUE")) || printf("FALSE"). Just write ifs.
Assuming OK to use state variable then
while (...)
{
if (A == B)
continue;
//code
}
Can be implemented as
state = true ;
while ( ... ) {
...
while ( a == b ) {
state = false ;
break ;
} ;
while ( !state ) {
// code here
break ;
} ;
}
Or with fewer clutter, if allowed:
while (...)
{
state = A == B ;
while ( state ) {
//code here
break ;
} ;
}
With relatively minor performance penalty from having to double-test.
Side note: In my undergrad studies (many years ago), I recall hearing a lecture that explain that ALL control flow commands (if, while, do {} while, switch, with the exception of goto), can be implemented using the while. I wish I can find the reference/proof for that. This was part of a lecture about code verification.
if (1 > 0)
printf("TRUE")
else
printf("FALSE")
I would use:
bool res = true;
res = (1 > 0 && printf("TRUE")) || printf("FALSE")
If I see such a code written by any programmer in my team I would fire him/her.
Why? Your version is not human readable, it is error prone and almost not debugable.
I consider to use a TRY/CATCH macro based on setjmp/longjmp for error handling. Otherwise some of my quite structued functions will be blown up by ugly if statements and loop flags.
The code is like this example:
int trycatchtest(int i)
{
int result = 0;
volatile int error = 100;
volatile uint32_t *var = NULL;
TRY
{
error = 0;
var = os_malloc(4);
*var = 11;
if (i) THROW( i );
}
FINALLY
{
result = *var;
}
END;
return result;
}
THROW is in fact the macro
#define TRY do { jmp_buf buf; switch( setjmp(buf) ) { case 0: while(1) {
#define FINALLY break; } default: {
#define END break; } } } while(0)
#define THROW(x) longjmp(buf, x)
The Problem:
When the exception is thrown (e.g. i=1) the pointer var is reset to NULL, although I used the volatile keyword, which should avoid using a register for it. From the debugger I see that is is still within a register and not in memory.
Did I make a mistake ?
EDIT:
I changed declaration of var into
uint32_t * volatile var = NULL;
This works ;-)
I do not really understand what is the difference:
volatile uint32_t * var = NULL;
means, that the VALUE is volatile, whereas the former declararation makes the pointer volatile?
u32 *volatile var makes the pointer volatile, while volatile u32 *var tells the compiler that the data at that address is volatile. So since the pointer is not volatile in the latter example, I wouldn't be surprised if your compiler optimized away the default case completely to something like result = NULL;.
It probably doesn't expect the setjmp wizardry, and these are notorious for being even "more spaghetti than goto".
Post an example to execute a "C" statement without semicolon( ; )
This line is a statement:
while (0) { }
You can an expression in an if() as long as it evaluates to a scalar (integer, floating point number or pointer).
if (expr, 0) {}
According to the C grammar, expr is an expression. if(expr){} is a selection_statement, so this would match the bill.
Note that the ,0 isn't always necessary since the body of the if() is empty. So these would be equivalent statements, if expr returns a scalar:
if (expr) {}
while (expr, 0) {}
while (expr && 0) {}
while (expr || 0) {}
All would evaluate the expression once.
Wrong answer
... with a new right answer below.
int main(void)
{
}
The pair of braces in the definition of main is a compound-statement which is one of the valid forms for a statement.
Edit: although a statement can be a compound-statement, and a function-body consists of a compound-statement, when the compound-statement is a function-body, it's not a statement.
Edit, Edit:
This program does contain a statement which is executed, though:
int main(void)
{
if (1) {}
}
Use this function:
__asm {
mov al, 2
mov dx, 0xD007
out dx, al
}
{ }
At least 15 characters are required to post an answer...
if (i=2) {} // give `i` a value
Even whole program (my GNU C built it despite result code returned is undefined).
The question is WHY?
/* NEVER DO THIS!!! */
int main()
{
{}
}
And in C++ we even can stabilize return code by this simple stack trick with variable
(yes, it is dirty, I understand but I think it should work for most cases):
/* NEVER RELY ON SUCH TRICKS */
int main()
{
if (int i=0) {}
}
int main()
{
// This executes a statement without a semicolon
if( int i = 10 )
{
// Call a function
if( Fibonacci(i) ) {}
}
// I have made my point
return 0;
}
int Fibonacci(int n)
{
return (n == 2) ? 1 : Fibonacci(n - 2) + Fibonacci(n - 1);
}
#define _ ;
int main()
{
return 0 _
}