I'm writing a function that is suppose to print out the description of a programs execution. A function in my program uses 0
as a signal for a base-10 numeric conversion.
I would like my program to have friendly output, and tell the user if a number has been converted to base 10, instead of letting the program say the number was converted from base 0.
When I attempt to compile this code, I get an error message which says 'expression is not assignable'.
I'm compiling on command line with cc compiler
Apple LLVM version 7.3.0 (clang-703.0.29)
Any idea what this error means and how to correct? Thanks.
void foo( int base ){
int theBase;
base == 0 ? theBase = 10: theBase = base;
printf("%s%d\n", "The base is ", theBase)
}
error message:
error: expression is not assignable
base == 0 ? theBase = 10: theBase = base;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ^
What you are doing here is a conditionnal assignation.
Usually you can do it like that:
if (base == 0)
theBase = 10;
else
theBase = base;
Here you chosed to use a ternary expression. It does work a bit like an if/else structure, but it is really different.
The ternary return a value, it's not made to execute code based on a condition. No, it return a value based on a condition.
So here, you have to do:
theBase = (base == 0 ? 10 : base);
(the parenthesis are not required, but it's a lot better to avoid error).
In fact, you can make a ternary execute code, in a multiple way, like returning a function:
int my_function()
{
printf("Code executed\n");
return (10);
}
/* ... */
theBase = (base == 0 ? my_function() : base);
EDIT:
And yes you can use that code:
base == 0 ? (theBase = 10) : (theBase = base);
But it's pretty useless to use a ternary in that case, because you still have to duplicate the theBase = X
code.