Compiler warning - suggest parentheses around assignment used as truth value

CCompiler ConstructionCompiler Warnings

C Problem Overview


When I try to compile the piece of code below, I get this warning:

warning: suggest parentheses around assignment used as truth value

Why does this happen? This is a rather common idiom, I believe. I even use something like it earlier on my code.

struct PIDList* 
getRecordForPID(struct PIDList* list, pid_t pid) {
	while(list = list->next)
		if (list->pid == pid)
			return list;

	return NULL;
}

C Solutions


Solution 1 - C

Be explicit - then the compiler won't warn that you perhaps made a mistake.

while ( (list = list->next) != NULL )

or

while ( (list = list->next) )

Some day you'll be glad the compiler told you, people do make that mistake ;)

Solution 2 - C

While that particular idiom is common, even more common is for people to use = when they mean ==. The convention when you really mean the = is to use an extra layer of parentheses:

while ((list = list->next)) { // yes, it's an assignment

Solution 3 - C

It's just a 'safety' warning. It is a relatively common idiom, but also a relatively common error when you meant to have == in there. You can make the warning go away by adding another set of parentheses:

while ((list = list->next))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionF. P.View Question on Stackoverflow
Solution 1 - CErikView Answer on Stackoverflow
Solution 2 - CgeekosaurView Answer on Stackoverflow
Solution 3 - CCarl NorumView Answer on Stackoverflow