Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execution direction of && Condition [duplicate]

Possible Duplicate:
Logical comparisons: Is left-to-right evaluation guaranteed?

I have been taught that for every C function arguments, Rightmost argument will be executed/processed first and it progresses towards left. Right part will be executed first and it progresses towards left.

Is this applicable to conditions like && and || ??

If I am writing a C++ Code, I check for NULL condtion first and then in next if I perform my action. for e.g.

 if( CommDevice != NULL)
   {
      if(CommDevice->isOpen == TRUE)
         { 
                //Do Something
         }

   }

Can I convert this in if((CommDevice != NULL) && (CommDevice->isOpen == TRUE) )

That "Code executes from Right to Left" fear is stopping me coz what if CommDevice is NULL and I am trying to access a member of NULL. It will generate exception.

like image 272
Swanand Avatar asked Nov 07 '12 06:11

Swanand


People also ask

What is the order of direction in which code is executed?

Software has an order of execution. This is the program sequence, meaning the order in which your lines of code will be executed.

What is the sequence of execution?

A sequence is an ordered list of something. Sequential execution means that each command in a program script executes in the order in which it is listed in the program. The first command in the sequence executes first and when it is complete, the second command executes, and so on.

What is good execution?

The main requirements for successful execution are: 1) clear goals for everyone in the organization, that are supportive of the overall strategy; 2) a means of measuring progress toward those goals on a regular basis; and 3) clear accountability for that progress. Those are the basics.


1 Answers

I have been taught that every C function takes argument from right to left. Right part will be executed first and it progresses towards left.

This is 100% not true. The order of argument evaluation is unspecified!

The order of && and || is defined because it forms a sequence point. First the left is evaluated, and if not short-circuiting then the right is evaluated.

if((CommDevice != NULL) && (CommDevice->isOpen == TRUE) )

This is correct.

like image 139
Pubby Avatar answered Sep 30 '22 01:09

Pubby