Assignments in conditions (assignments in conditions) C C ++ C # Java PHP

Lecture

1. assignment in C conditions

#include <stdio.h>

int main (void) {

int h = 0;
int y;
if (h = 1) {y = 9;}

printf ("% d", h);
return 0;
}

It worked

Success time: 0 memory: 2160 signal: 0

  one 

2. assignments in C ++ conditions

#include <iostream>
using namespace std;
#include <stdio.h>
int main () {
// your code goes here
int h = 0, y;
if (h = 1) y = 9;

std :: cout << h << std :: endl;

return 0;
}

work fine

Success time: 0 memory: 3456 signal: 0

  one 

3. assignments in C # conditions

using System;
using System.Text;
public class Test
{
public static void Main ()
{
int h = 0, y;
if (h = 1) y = 9;
Console.WriteLine (h);
return;
}
}

Will cause an error

  prog.cs (8,7): warning CS0665: Assignment in conditional expression is always constant.  Did you mean to use == 'instead?
 prog.cs (8,7): error CS0029: Cannot implicitly convert type `int 'to` bool'
 Compilation failed: 1 error (s), 1 warnings 

4. assignments in conditions in JAVA

package test;

import java.util. *;
import java.lang. *;
import java.io. *;

/ * Name "Main" only if the class is public. * /
class Ideone
{
public static void main (String [] args) throws java.lang.Exception
{

int h = 0, y;
if (h = 1) y = 9;

System.out.println (h);

}
}

causes an error

Compilation error time: 0.09 memory: 320576 signal: 0

  Main.java:14: error: incompatible types: int cannot be converted to boolean
		 if (h = 1) y = 9;
		      ^
 1 error 

5. assignment under conditions in PHP

So, all of you know how conditions and comparison operators work in php.
In the example below, the value of the $ var variable is reduced to a boolean, and if it is true, the condition is satisfied.
if ($var){...}

This example compares the values ​​of the $ var variable and the result of foo (), and if they are equivalent, the condition is satisfied.
if ($var == foo()){...}

Here, in the condition of the $ var variable, the result of foo () is assigned, after which the value of $ var is reduced to Boolean, and if it is true, the condition is satisfied.
if ($var = foo()){...}

Although the last example is valid in php, it is really hard to read, because there are no comparison operators in the condition. Often this code is an error, and the programmer actually meant
if ($var == foo()){...}

When comparing a variable with a boolean value based on the type, it is often written like this
if (true === $var){...}

This is done precisely in order to avoid the random assignment of $ var to the value of true, for example
if ($var = true){...}

167
0

Order a test or course / diploma work

find out the cost and
I need to get work done
or
I am an expert in this field and
I want to earn

Without intermediaries, but with a guarantor option

Rating 9 of 10. count vote: 2
You vote:



Comments (0)


To leave a comment

To reply

Programming Styles and Techniques

Terms: Programming Styles and Techniques