gcc - In C, in the 'if' statement, why invert the constant of test and the variable, e.g. if (10 == val) {}? -


in c, if statement, sometime can see test 'value placed before variable test, brings optimization (gcc compiler), 1 ? (but decreases readability think).

example:

if ( 10 == val) {} 

thanks,

it doesn't have optimization, it's trick used avoid accidental assignment , it's called yoda convention or yoda conditions. prevents accidental assignment because

if (value = 10) 

would compile , assign 10 value not want if meant if (value == 10) (although compilers can warn , suggest parentheses avoid ambiguity), this

if (10 = value) 

would not.

since compilers can warn, , when have experience uncommon mistake advice against this. because it's difficult read , doesn't feel natural. careful , use normal conditions like

if (value == 10) 

and safe, enable warnings in compiler prevent accidental assignment. see equivalent talking yoda, like in comment , can see why in natural language uncomfortable, in code.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -