Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of "if (x) { … }" where x is an integer in C++? [duplicate]

I saw some c++ syntax that puzzled me

int x = 10;
if(x){ //this line confused me
//code 
}
else{
//code 
}

i don't understand how this is valid code, what does the if(x) do?

like image 501
Sam Liokumovich Avatar asked Sep 21 '25 02:09

Sam Liokumovich


1 Answers

An int converts implicitly to a bool. Any int that's non-zero evaluates to true. A zero integer converts to false. In your case, that line basically tests whether x is different from zero, and it is equivalent with

if(x != 0) ...
like image 107
vsoftco Avatar answered Sep 22 '25 15:09

vsoftco