> It's true that the looser scoping rules of langauges like matlab and 
python 
> can be convenient.  On the whole I prefer tighter scoping rules like C++ 
> though: they make code easier to reason about by making the data 
> flow more local. 

The situation I met was not as clear as you describe it here.
For some testing purposes I had defined i before defining the function:

    julia> i = 10;

    julia> function testfun1(x::Vector{Float64})
               for i = 1:length(x)
                   if x[i] == 0.0
                       break
                   end
               end
               return i-1
           end;

    julia> testfun1([1.0, 2.0, 3.0, 0.0, 1.0])
    9

and it took me some time before I realized that the answer came from 
outside the function.
That behavior can really lead to very difficult testing situations.

I don't know whether something like this can happen in C/C++.


On Saturday, May 17, 2014 2:37:13 PM UTC+2, Chris Foster wrote:
>
> On Sat, May 17, 2014 at 9:59 PM, Hans W Borchers 
> <[email protected]<javascript:>> 
> wrote: 
> > Yesterday I implemented a function calculating arc length of curves (to 
> the 
> > last digit) when I came across the following stumbling blocks. Image the 
> > following function where I leave a for-loop with a 'break' statement: 
> > 
> >     function testfun1(x::Vector{Float64}) 
> >         for i = 1:length(x) 
> >             if x[i] == 0.0 
> >                 break 
> >             end 
> >         end 
> >         return i-1 
> >     end 
>
> For this particular example, I'd suggest you just return i-1 directly 
> inside the loop: 
>
> function testfun1(x::Vector{Float64}) 
>     for i = 1:length(x) 
>         if x[i] == 0.0 
>             return i-1 
>         end 
>     end 
>     return length(x)-1 # Or other special case for when 0 isn't found 
> end 
>
> Using an early return like this is really quite powerful, especially when 
> you have a deeply nested set of loops.  I use it all the time in C++. 
>
> > I understand that the scope of the loop variable is restricted to the 
> loop 
> > itself. What is the best way to "export"  i  to the outside? For the 
> moment 
> > I settled with defining i before the loop. 
>
> Yes, if you want i accessible outside a loop, you'll just have to declare 
> it in the outer scope.  AFAIK you've done the right thing there, though 
> initializing i to a default would be more concise and wouldn't fail if the 
> input array is empty (unless that's intentional). 
>
> > This works, but I must admit it runs against my gut feeling and 
> > experience with other scientific programming languages. 
>
> It's true that the looser scoping rules of langauges like matlab and 
> python 
> can be convenient.  On the whole I prefer tighter scoping rules like C++ 
> though: they make code easier to reason about by making the data 
> flow more local. 
>
> ~Chris 
>

Reply via email to