Cristian
Cristian

Reputation: 9

Conditions in an if statement

I'm looking through this article (https://spin.atomicobject.com/2012/06/18/solving-sudoku-in-c-with-recursive-backtracking/) explaining a backtracking approach to solve a sudoku puzzle in C and I had a couple of questions about conditions in if statements.

He uses if(puzzle[row][column]), I am unsure as to what it is checking. If a number exists in that position it will continue? For this I would have thought to use != null to check that it's not empty

He also uses a function call inside an if statement: if(isValid(nextNum, puzzle, row, column) Does this mean if the function is successful it executes what's inside the if?

Upvotes: 0

Views: 102

Answers (2)

JeremyP
JeremyP

Reputation: 86651

Because, in C int expressions can be used in place of boolean expressions with 0 being false and anything else being true, if(puzzle[row][column]) is an idiomatic way of writing

if(puzzle[row][column] != 0)

I prefer the latter because the former does seem to confuse people not familiar with the idiom.

If a number exists in that position it will continue? For this I would have thought to use != null

The values in a cell are number - ints in fact. He uses zero as a convention for "not filled in yet". If the values in the array were pointers, I would agree, with if(puzzle[row][column] != NULL) but they aren't pointers.

Upvotes: 3

Andrew Cottrell
Andrew Cottrell

Reputation: 3413

In C conditionals 0 is false and anything non-zero is true. puzzle is a 2-dimensional array of int. If the int is 0 then the conditional evaluates as false. If the int is non-zero then the conditional evaluates as true.

Upvotes: 0

Related Questions