What does the line seed[0] *= 16807 do - c

in the following code:
float sfrand( int *seed )
{
float res;
seed[0] *= 16807;
*((unsigned int *) &res) = ( ((unsigned int)seed[0])>>9 ) | 0x40000000;
return( res-3.0f );
}
source: http://iquilezles.org/www/articles/sfrand/sfrand.htm

seed[0] is same as *seed, that is the first integer (possibly the only one, if it doesn't point to an array) pointed to by seed pointer.
*= operator is "assignment by product" operator,
seed[0] *= 16807; is same as
*seed = *seed * 16807;, which is what the line you ask about does.
The whole function is a simple algorithm to generate pseudo-random numbers, it seems. The purpose of modifying the seed is, that next call will produce a different pseudo-random number.

The seed[0] *= 16807; line is just a shortcut for seed[0] = seed[0] * 16807;
Here's a list of similar constructs: https://www.programiz.com/c-programming/c-operators

*= is a composite operator for multiplication. In this operator, the result that left operand multiplies to right operand will be stored with left operand. So in this statement seed[0] *= 1680;, left operand is seed[0], right operand is 1680. After this statement is executed, seed[0] will be equal to seed[0] * 1680. The is a similar statement for it:
seed[0] = seed[0] * 1680;
We have some composite operators: +=, -=,/=, ... that are working in the same behavior.

Related

How to print only the first 2 digit of a double in C

for (total = 0; total < amount; total++){
int flip = rand() % 2;
if (flip == 1){
heads++;
}
else{
tails++;
}
}
// Percentage calculation
percentage_heads = heads/amount * 100;
percentage_tails = tails/amount * 100;
printf("Tails: %d\nHeads: %d (%.2f percent)", tails, heads, percentage_heads);
Whenever variable "percentage_heads" equals 100 it's prints out fine but for anything else (EX: 50.01, 34.87, etc.) it just prints 0.00. How can I get the program to print out the true percentage?
Here the issue is the below calculation evaluates from left to right based on the implicit type conversion.
percentage_heads = heads/amount * 100;
^ ^ ^ ^
double int int int
Above one evaluates as, heads/amount to 0 or 1 and multiplied with 100, results in either 0 or 100 respectively.
So, the solution is by using a explicit type conversion or by making one of values in the expression as float or double to make use of automatic implicit type conversion.
// explicit type conversion
percentage_heads = (double) heads/amount * 100;
This evaluates considering the expression as double and will provide the result with decimal values.
// implicit type conversion
percentage_heads = 100.0 * heads/amount;
^ ^ ^ ^
double float int int
When this is evaluated from left to right, 100.0 is hit first and the operation is performed based on it's type i.e., float and hence it provides the result with proper decimal values.
Note:
// thought implicit type conversion would work but not
percentage_heads = heads/amount * 100.0;
^ ^ ^ ^
double int int float
Here as the expression is evaluated from left to right, first the heads/amount is hit and gets evaluated as 0 or 1 which would still result in the values as 0.0 or 100.0.

Increment function with pointers not working

I am trying to find the number of digits in a given number through the use of pointers.
This code below will give the correct output,
void numDigits(int num, int *result) {
*result = 0;
do {
*result += 1;
num = num / 10;
} while (num > 0);
}
However, if I change the *result += 1; line to *result++;, the output will no longer be correct and only give 0.
What is going on here?
In C/C++, precedence of Prefix ++ (or Prefix --) has higher priority than dereference (*) operator, and precedence of Postfix ++ (or Postfix --) is higher than both Prefix ++ and *.
If p is a pointer then *p++ is equivalent to *(p++) and ++*p is equivalent to ++(*p) (both Prefix ++ and * are right associative).
*result++ is interpreted as *(result++).
the order of evaluation is the increment is first, then you dereference the pointer, the value of the pointer stays the same for the line in the expression if it's a postfix.
what you are trying to do is to increment the dereference of the pointer so you need to put the parenthesis on the dereference then increment it, like this: (*result)++;

How are these two methods to find what power of 2 a number is, different?

So, let's say I have a number N that's guaranteed to be a power of 2 and is always greater than 0. Now, I wrote two C methods to find what power of 2 N is, based on bitwise operators -
Method A -
int whichPowerOf2(long long num) {
int ret = -1;
while (num) {
num >>= 1;
ret += 1;
}
return ret;
}
Method B -
int whichPowerOf2(long long num) {
int idx = 0;
while (!(num & (1<<idx))) idx += 1;
return idx;
}
Intuitively, the two methods seem one and the same and also return the same values for different (smaller) values of N. However, Method B doesn't work for me when I try to submit my solution to a coding problem.
Can anyone tell me what's going on here? Why is Method A right and Method B wrong?
The problem is with this subexpression:
1<<idx
The constant 1 has type int. If idx becomes larger than the bit width of an int, you invoked undefined behavior. This is specified in section 6.5.7p3 of the C standard regarding bitwise shift operators:
The integer promotions are performed on each of the operands. The type
of the result is that of the promoted left operand. If the value of
the right operand is negative or is greater than or equal to the width
of the promoted left operand, the behavior is undefined.
Change the constant to 1LL to give it type long long, matching the type of num.
while (!(num & (1LL<<idx))) idx += 1;
In your Method B, the following line can cause undefined behaviour:
while (!(num & (1<<idx))) idx += 1;
Why? Well, the expression 1<<idx is evaluated as an int because the constant 1 is an int. Further, as num is a long long (which we'll assume has more bits than an int), then you could end up left-shifting by more than the number of bits in an int.
To fix the issue, use the LL suffix on the constant:
while (!(num & (1LL<<idx))) idx += 1;

What happens when you assign a (float x1, float x2) to a float r in C? [duplicate]

What does the , operator do in C?
The expression:
(expression1, expression2)
First expression1 is evaluated, then expression2 is evaluated, and the value of expression2 is returned for the whole expression.
I've seen used most in while loops:
string s;
while(read_string(s), s.len() > 5)
{
//do something
}
It will do the operation, then do a test based on a side-effect. The other way would be to do it like this:
string s;
read_string(s);
while(s.len() > 5)
{
//do something
read_string(s);
}
The comma operator will evaluate the left operand, discard the result and then evaluate the right operand and that will be the result. The idiomatic use as noted in the link is when initializing the variables used in a for loop, and it gives the following example:
void rev(char *s, size_t len)
{
char *first;
for ( first = s, s += len - 1; s >= first; --s)
/*^^^^^^^^^^^^^^^^^^^^^^^*/
putchar(*s);
}
Otherwise there are not many great uses of the comma operator, although it is easy to abuse to generate code that is hard to read and maintain.
From the draft C99 standard the grammar is as follows:
expression:
assignment-expression
expression , assignment-expression
and paragraph 2 says:
The left operand of a comma operator is evaluated as a void expression; there is a sequence point after its evaluation. Then the right operand is evaluated; the result has its type and value. 97) If an attempt is made to modify the result of a comma operator or to access it after the next sequence point, the behavior is undefined.
Footnote 97 says:
A comma operator does not yield an lvalue.
which means you can not assign to the result of the comma operator.
It is important to note that the comma operator has the lowest precedence and therefore there are cases where using () can make a big difference, for example:
#include <stdio.h>
int main()
{
int x, y ;
x = 1, 2 ;
y = (3,4) ;
printf( "%d %d\n", x, y ) ;
}
will have the following output:
1 4
The comma operator combines the two expressions either side of it into one, evaluating them both in left-to-right order. The value of the right-hand side is returned as the value of the whole expression.
(expr1, expr2) is like { expr1; expr2; } but you can use the result of expr2 in a function call or assignment.
It is often seen in for loops to initialise or maintain multiple variables like this:
for (low = 0, high = MAXSIZE; low < high; low = newlow, high = newhigh)
{
/* do something with low and high and put new values
in newlow and newhigh */
}
Apart from this, I've only used it "in anger" in one other case, when wrapping up two operations that should always go together in a macro. We had code that copied various binary values into a byte buffer for sending on a network, and a pointer maintained where we had got up to:
unsigned char outbuff[BUFFSIZE];
unsigned char *ptr = outbuff;
*ptr++ = first_byte_value;
*ptr++ = second_byte_value;
send_buff(outbuff, (int)(ptr - outbuff));
Where the values were shorts or ints we did this:
*((short *)ptr)++ = short_value;
*((int *)ptr)++ = int_value;
Later we read that this was not really valid C, because (short *)ptr is no longer an l-value and can't be incremented, although our compiler at the time didn't mind. To fix this, we split the expression in two:
*(short *)ptr = short_value;
ptr += sizeof(short);
However, this approach relied on all developers remembering to put both statements in all the time. We wanted a function where you could pass in the output pointer, the value and and the value's type. This being C, not C++ with templates, we couldn't have a function take an arbitrary type, so we settled on a macro:
#define ASSIGN_INCR(p, val, type) ((*((type) *)(p) = (val)), (p) += sizeof(type))
By using the comma operator we were able to use this in expressions or as statements as we wished:
if (need_to_output_short)
ASSIGN_INCR(ptr, short_value, short);
latest_pos = ASSIGN_INCR(ptr, int_value, int);
send_buff(outbuff, (int)(ASSIGN_INCR(ptr, last_value, int) - outbuff));
I'm not suggesting any of these examples are good style! Indeed, I seem to remember Steve McConnell's Code Complete advising against even using comma operators in a for loop: for readability and maintainability, the loop should be controlled by only one variable, and the expressions in the for line itself should only contain loop-control code, not other extra bits of initialisation or loop maintenance.
It causes the evaluation of multiple statements, but uses only the last one as a resulting value (rvalue, I think).
So...
int f() { return 7; }
int g() { return 8; }
int x = (printf("assigning x"), f(), g() );
should result in x being set to 8.
As earlier answers have stated it evaluates all statements but uses the last one as the value of the expression. Personally I've only found it useful in loop expressions:
for (tmp=0, i = MAX; i > 0; i--)
The only place I've seen it being useful is when you write a funky loop where you want to do multiple things in one of the expressions (probably the init expression or loop expression. Something like:
bool arraysAreMirrored(int a1[], int a2[], size_t size)
{
size_t i1, i2;
for(i1 = 0, i2 = size - 1; i1 < size; i1++, i2--)
{
if(a1[i1] != a2[i2])
{
return false;
}
}
return true;
}
Pardon me if there are any syntax errors or if I mixed in anything that's not strict C. I'm not arguing that the , operator is good form, but that's what you could use it for. In the case above I'd probably use a while loop instead so the multiple expressions on init and loop would be more obvious. (And I'd initialize i1 and i2 inline instead of declaring and then initializing.... blah blah blah.)
I'm reviving this simply to address questions from #Rajesh and #JeffMercado which i think are very important since this is one of the top search engine hits.
Take the following snippet of code for example
int i = (5,4,3,2,1);
int j;
j = 5,4,3,2,1;
printf("%d %d\n", i , j);
It will print
1 5
The i case is handled as explained by most answers. All expressions are evaluated in left-to-right order but only the last one is assigned to i. The result of the ( expression )is1`.
The j case follows different precedence rules since , has the lowest operator precedence. Because of those rules, the compiler sees assignment-expression, constant, constant .... The expressions are again evaluated in left-to-right order and their side-effects stay visible, therefore, j is 5 as a result of j = 5.
Interstingly, int j = 5,4,3,2,1; is not allowed by the language spec. An initializer expects an assignment-expression so a direct , operator is not allowed.
Hope this helps.

Same as i++ but for more complex operation

I'm not facing any problem. This question is just about C language
Let's say I have a function like:
int func()
{
static int i = 1;
return(i++);
}
Now, instead of doing i++ (i+=1) I'd like to do i *= 42; but still return the value before the multiplication.
I'm wondering if there is a way to do it the same way that i++ works (in one expression, take value of i and then do i *= 42).
Postfix ++ and -- are the only C operators that modify an object and yield that object's previous value. If you want to do that for anything other than incrementing or decrementing by 1, you'll have to store the previous value in a temporary.
If you wanted to design your own language, you could implement a "reverse comma" operator that yields its left operand rather than its right operand. (The existing comma operator evaluates its left operand, then evaluates its right operand, then yields the value of the right operand.)
For example, if the "reverse comma" were spelled ,,, you could do:
return i ,, i *= 42; /* THIS IS NOT C */
int func()
{
static int i = 1;
int tmp = i;
i *= 42;
return tmp;
}
An assignment is an expression is C. So you could code
int func() {
static int i = 1;
return(i *= 42);
}
Of course if you wanted to return i before multiplying it you need another variable.

Resources