Recently I found some code that is very interesting to me, but I can't properly understand it, so can someone please explain it to me?
It's Conway's Game of Life. I think this row can be like a question and 1 meaning true and 0 meaning false; is that correct? But why is there no bool?
void iterGen(int WIDTH, int HEIGHT, char curMap[WIDTH][HEIGHT])
{
int i, j;
char tempMap[WIDTH][HEIGHT];
for (i = 0; i < WIDTH; i )
{
for (j = 0; j < HEIGHT; j )
{
int neighbors = 0;
neighbors = curMap[i 1][j 1] == '*' ? 1 : 0;
neighbors = curMap[i 1][j] == '*' ? 1 : 0;
neighbors = curMap[i 1][j-1] == '*' ? 1 : 0;
neighbors = curMap[i][j 1] == '*' ? 1 : 0;
neighbors = curMap[i][j-1] == '*' ? 1 : 0;
neighbors = curMap[i-1][j 1] == '*' ? 1 : 0;
neighbors = curMap[i-1][j] == '*' ? 1 : 0;
neighbors = curMap[i-1][j-1] == '*' ? 1 : 0;
if (curMap[i][j] == ' ')
{
tempMap[i][j] = neighbors == 3 ? '*' : ' ';
}
else if (curMap[i][j] == '*')
{
tempMap[i][j] = neighbors < 2 || neighbors > 3 ? ' ' : '*';
}
}
}
for (i = 0; i < WIDTH; i )
{
for (j = 0; j < HEIGHT; j )
{
curMap[i][j] = tempMap[i][j];
}
}
}
CodePudding user response:
First, a couple of comments.
neighbors = curMap[...][...] == '*' ? 1 : 0
is a redundant way of writing
neighbors = curMap[...][...] == '*'
since the comparison operators already return 1
or 0
.
But neither are as clear as
if ( curMap[...][...] == '*' ) neighbors;
1 meaning true and 0 meaning false; is that correct? But why is there no bool?
Not quite. 0
is false (including 0
as a pointer, NULL
). All other values are true.
Now, on to the question.
But why there is no bool?
But there is: _Bool
.
stdbool.h
provides bool
as an alias, as well as the macros true
and false
.
#include <stdbool.h>
#include <stdio.h>
bool flag = true;
if ( flag )
printf( "True\n" );
else
printf( "False\n" );
Demo on Compiler Explorer
Note that none of the variables in the snippet you posted are booleans, so I have no idea why that code was included in your question.
CodePudding user response:
Just like in most other languages, in C any value that is not 0 can be considered as true.
if ( 20 ) {
// true
}
if ( -1 ) {
// true
}
if ( 'c' ) {
// true
}
if ( "string" ) {
// true
}
if ( 0 ) {
// false
}
if ( '\0' ) { // null terminator, a char with a value of 0
// false
}
if ( NULL ) { // value of a null pointer constant
// false
}
Bool is just a way to make code more readable.