Thread: defined behaviour

  1. #1
    Registered User
    Join Date
    Apr 2019
    Posts
    808

    defined behaviour

    lets suppose we have the following silly function
    Code:
    void func()
    {
         int idiff = 0, x = 7, y = 2;
         
         idiff = x/y;
    im sure i read or was told that the value of idiff would be undefined. However, i seem to come across it a lot and used to get the answer 3 in this case.

    second question
    suppose we have have the following if statement
    Code:
    if ( func(p) && p > iMax )
    {
          //some code.....
    is that the same as
    Code:
    //a)                        or            b)
    if ( func(p) )                          if ( p > iMax )
    {                                          {
          if ( p > iMax )                       if ( func(p) )
          {                                         {
    i know it seems a trivial thing but it could save func being called if p is less than iMax

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    > im sure i read or was told that the value of idiff would be undefined.
    It looks fine to me.

    Sure, if y is ever zero, then you're on your own at that point.

    > i know it seems a trivial thing but it could save func being called if p is less than iMax
    && and || have very specific semantics.
    Specifically, the left hand side is ALWAYS evaluated first.

    In the case of &&, the right hand side is only evaluated if the left is true.
    In the case of ||, the right hand side is only evaluated if the left is false.

    So it would seem you mean to have
    if ( p > iMax && func(p) )
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 07-19-2015, 05:51 PM
  2. Functor Behaviour
    By nickman in forum C++ Programming
    Replies: 7
    Last Post: 11-22-2014, 08:12 AM
  3. undefined behaviour.
    By juice in forum C Programming
    Replies: 3
    Last Post: 12-21-2011, 01:03 PM
  4. Bizarre MPI Behaviour
    By maverick_starst in forum C++ Programming
    Replies: 9
    Last Post: 07-20-2009, 07:41 PM
  5. Stack behaviour
    By pfs in forum Linux Programming
    Replies: 12
    Last Post: 07-06-2009, 05:34 AM

Tags for this Thread