2

Sometimes in JavaScript or C# code I will see a "1==1" conditional statement.

C# example:

if (!IsPostBack || 1==1)

I know that in Sql statements, 1=1 can be used when dynamically building queries or when creating sql injection attacks, but I don't understand the practical usage of a test that always evaluates to true in C# or JavaScript.

Community
  • 1
  • 1
Jake
  • 4,829
  • 2
  • 33
  • 44
  • @dystroy: could you elaborate on that? How would the shown code be an error without it? I have never seen a usage such as the one you describe. – Daniel Hilgarth Jul 22 '13 at 18:35
  • 2
    Sometimes people use a simple mathematical check like that while debugging to quickly force a block of code to run or prevent it from running (1==0) without altering anything else inside the statement. It would be sloppy to leave it in there permanently. – Ben Y Jul 22 '13 at 18:38

3 Answers3

9

There is no value. This makes the condition to be always true, so you simply could remove the if.

I guess it has been added while debugging a problem to force the execution of this particular branch and it simply has been forgotten to remove it. I would call it a bug.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
  • 1
    @newStackExchangeInstance: What kind of question is that? You should be asking why it is there at all. `true` would have been just the same and both make no sense when being left permanently in the code. Why the developer chose to use `1==1` instead of `true` is impossible for me to know. – Daniel Hilgarth Jul 22 '13 at 18:42
2

Developer testing of the following:

  • The function/method/sub/etc gets executed no matter the "Real" parameter value
  • Seeing how your parameters would be effected by a False || True situation

The only real practical uses I see are:

  • Testing
  • SQL Injection, as you said
Elias
  • 2,602
  • 5
  • 28
  • 57
1

An if with a 1==1 conditional is a misuse of an if statement. Although syntactically sound, it removes the value of the if even being there.

As Daniel stated, it was probably used while debugging a particular portion of code. If it's left in production code it is likely a bug, otherwise it's a complete misuse of the if statement.

if ( !IsPostBack || 1==1)
{
    // Do Something
}

is equivalent to

//Do Something
Derek W
  • 9,708
  • 5
  • 58
  • 67