• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

Splatt

Member
After a night of debugging friend's code...

ipMTiffBz7KK6.gif
 

Kalnos

Banned
I have a face-to-face interview that's 2 hours long with 4 different developers each for 30 minutes coming up. Any advice on what kinds of questions to expect in that sort of time frame? This is an entry-level Software Engineering position.
 
Programming in Visual Basic 2010

uuDRhKy.png


So I what I need to do is to program it that the number of items I enter is less then 10 then what the value in the commission box is 1, if its more then that but under 41 then its 2, more then that but under 100 then its 4, more then 100 then its 8.

I'm not really sure what to do. I thought of doing this:

If Val(TextBox1.Text) < 10 Then
Val(Label6.Text) = 1
Else If
Val(TextBox1.Text) >10< 41 Then

But that leads to errors. I'm so confused. :(
 

Tamanon

Banned
Take off the >10 on there, if you're checking if it is less than 10, then the greater than 10 is superfluous(also would cause a problem on exactly 10. Beyond that, I don't know the Visual Basic syntax.
 
Take off the >10 on there, if you're checking if it is less than 10, then the greater than 10 is superfluous(also would cause a problem on exactly 10. Beyond that, I don't know the Visual Basic syntax.

I still did it and no cigar.

If Val(TextBox1.Text) < 10 Then
Label6.Text = 1
ElseIf
Val(TextBox1.Text) < 41
Label6.Text = 2

End If

It says an error right at 41.
 

Tamanon

Banned
I still did it and no cigar.

If Val(TextBox1.Text) < 10 Then
Label6.Text = 1
ElseIf
Val(TextBox1.Text) < 41
Label6.Text = 2

End If

It says an error right at 41.

Hmm, not familiar with it, but wouldn't you have to continue the If/Elseif statement until the cases are satisfied? Would have to add the <100 and final else statement to satisfy it.
 

Kalnos

Banned
are you just missing a 'Then' on the ElseIf?

If Val(TextBox1.Text) < 10 Then
Label6.Text = 1
ElseIf Val(TextBox1.Text) < 41 Then
Label6.Text = 2
 
Solved it.

Here's my code:

Code:
Public Class Form1

 
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim earnings As Double
        Dim earnings2 As Double
        Dim earnings3 As Double
        If Val(TextBox1.Text) < 10 Then
            Label6.Text = 1
        ElseIf Val(TextBox1.Text) < 41 Then
            Label6.Text = 2
        ElseIf Val(TextBox1.Text) < 100 Then
            Label6.Text = 4
        ElseIf Val(TextBox1.Text) > 100 Then
            Label6.Text = 8
        End If
        earnings = Val(TextBox1.Text) * 10
        earnings2 = Val(TextBox1.Text) / 1000
        earnings3 = Val(TextBox1.Text) * Val(Label6.Text) / 10
        Label5.Text = String.Format("{0:C}", earnings)
        Label7.Text = String.Format("{0:C}", earnings3)
    End Sub
End Class
 

Slavik81

Member
I'm trying to remember a word I recently used to describe code in which the focus is the result, not the implementation. Such code should be concise, and readable because it doesn't repeat implementation details over and over.

I think the word began with a 'C'. It's driving me mad. Any thoughts?
 
I'm trying to remember a word I recently used to describe code in which the focus is the result, not the implementation. Such code should be concise, and readable because it doesn't repeat implementation details over and over.

I think the word began with a 'C'. It's driving me mad. Any thoughts?

Declarative programming?
 

usea

Member
Anyone ever heard/used a raspberry pi as a webserver? I have two domains and I figure the pi should be enough to handle some messing about with for now.
I've put a webserver on it, but it wasn't public-facing. And I only loaded it a few times to see if it worked.

I was using Go, which has its own webserver in the net/http module and it's easy to compile for ARM.
 

Magni

Member
Anyone ever heard/used a raspberry pi as a webserver? I have two domains and I figure the pi should be enough to handle some messing about with for now.

My brother has one that he uses at a webserver but I don't know what exactly he does with it. I'll ask and report back.
 
I've put a webserver on it, but it wasn't public-facing. And I only loaded it a few times to see if it worked.

I was using Go, which has its own webserver in the net/http module and it's easy to compile for ARM.

It's going to be public facing but i honestly doubt I will receive a ton of traffic for it so it's mainly for messing around.

My brother has one that he uses at a webserver but I don't know what exactly he does with it. I'll ask and report back.

thanks.
 

injurai

Banned
Question on C/C++

If I'm coding in VS and using it to compile. Assuming I'm only using the standard libraries, the code is essentially portable if I rebuild the source in say linux with GCC. Correct?
 

Tamanon

Banned
Oh the frustration of messing around with various ways of doing the ROT13 conversion of a string and having different errors pop up. Then discovering 1 and a half hours later that there was a built-in function in Python of text.encode('rot13').

I was doing some Udacity stuff and the challenge was to make a webpage that did a ROT13 conversion. All the math replacements I tried kept messing with ASCII versus Unicode. Finally got it implemented though. Pretty happy, as a beginner.
 

Water

Member
Question on C/C++

If I'm coding in VS and using it to compile. Assuming I'm only using the standard libraries, the code is essentially portable if I rebuild the source in say linux with GCC. Correct?
Correct. If your code only uses standard libraries, it should build without issue in gcc or clang. (If you don't have a preference, use clang.) At most, they might warn you about some things which VS does not notice. Going the other way, developing on gcc or clang and trying to later build with VS doesn't necessarily go as smoothly. VS lacks support for a lot of standard language and library features. Most of that difference should disappear when VS2013 arrives though.
 

injurai

Banned
Correct. If your code only uses standard libraries, it should build without issue in gcc or clang. (If you don't have a preference, use clang.) At most, they might warn you about some things which VS does not notice. Going the other way, developing on gcc or clang and trying to later build with VS doesn't necessarily go as smoothly. VS lacks support for a lot of standard language and library features. Most of that difference should disappear when VS2013 arrives though.

Oh neat, glad I asked. Also what makes clang so great. I know in some regard it's precompile can give a sort of heightened syntax highlighting and error detection correct?
 

Water

Member
Oh neat, glad I asked. Also what makes clang so great. I know in some regard it's precompile can give a sort of heightened syntax highlighting and error detection correct?
clang is designed to be modular and to expose its capabilities easily to other tools. It's just one purpose of many that editors or their plugins can use clang to power their C++ syntax highlighters, intelligent autocompletion, etc. To carry out those tasks perfectly, a tool would actually have to understand all the nooks and crannies of C++. That has been a completely infeasible task for people writing editors or plugins, because it amounts to writing a substantial part of a full C++ compiler. So the usual thing to do has been to fake some level of understanding with a few simple approximation rules that get it right 95% of the time and fail the rest of the time. Since clang is a compiler and understands 100% of the language, allowing tools to tap into its knowledge enables them to produce perfect results.

Also, clang produces nicer error and warning messages and diagnostics than other major compilers, and is the first (so far only) compiler to reach full C++11 compatibility.
 

Sharp

Member
I'm trying to remember a word I recently used to describe code in which the focus is the result, not the implementation. Such code should be concise, and readable because it doesn't repeat implementation details over and over.

I think the word began with a 'C'. It's driving me mad. Any thoughts?
Declarative programming was the obvious one, but: constraint programming? Logic programming? Just plain old functional programming? Haskell? :p

Clang is (theoretically) nice because it has been designed from the ground up using modern compiler theory with the expectation that it will be run on modern, fast computers with lots of memory, while GCC has grown up incrementally over the course of decades around code that had to work on machines that had little in common with today's personal supercomputers. In practice, the code it produces still tends to be slower than GCC's, though it's catching up, and it doesn't work on nearly as many target architectures (but let's be honest--most people are working against x86).
Have fun with it. The parsing and storing of the data is just sort of ridiculous. If you have a global feed it's just so much data that it's hard to deal with. If you're getting it in raw NMEA format parsing it can be tough, and from my experience the open source parsers are pretty slow.

I was hoping to be able to concurrently update/insert AIS positions to the database, but whenever 2 transactions happen at once I get deadlocks galore. I'm not sure what I am doing wrong. I don't even know if JDBC supports snapshot isolation levels either. I basically have 1000 of those store proc calls in a single batch transaction. I was hoping to be able to execute multiple transactions at once to reduce the overhead from I/O across the network. I've basically just had to increase the batch size so that no actual concurrency occurs because of the frequency of the deadlocks.
UPDLOCK blocks on update. Based on http://msdn.microsoft.com/en-us/library/ms173763.aspx (your query is set to READ COMMITTED), my guess is that there are individual row locks interfering between the two transactions. Are you positive that concurrent updating is really going to improve efficiency if you select all the same rows? SQL Server has to acquire locks on the physical pages of the hard disk when it writes to them so unless the table is spread across multiple disks it may not be possible to physically commit the data to disk simultaneously. See http://blog.sqlauthority.com/2011/0...latch_sh-pagelatch_up-wait-type-day-12-of-28/. SQL Server is extremely complex and I strongly recommend you get a DBA at your company to take a look at what you're doing.
 

injurai

Banned
do any languages have a logical control that is something like

Code:
while(stuff) {
       //do stuff
} finish {
      //stuff to finish after loop
}

essentially an elegant way of doing one time concluding tasks, like updating a field after building it, or closing buffers. Surprised I have never seen stuff like this.

Wondering because it would make readability in my code a lot better (java/groovy atm)
 

Roquentin

Member
do any languages have a logical control that is something like

Code:
while(stuff) {
       //do stuff
} finish {
      //stuff to finish after loop
}

essentially an elegant way of doing one time concluding tasks, like updating a field after building it, or closing buffers. Surprised I have never seen stuff like this.

Wondering because it would make readability in my code a lot better (java/groovy atm)
What's wrong with
Code:
while(stuff) {
       // do stuff
}
// stuff to finish after loop
?
 

injurai

Banned
What's wrong with
Code:
while(stuff) {
       // do stuff
}
// stuff to finish after loop
?

oh, because It's stuff I only need to handling assuming the loop began.

otherwise I would need some sort of flag or have an outer if statement. But that would be sloppy imo.

if(condition to check) {
while(same condition) {

}
finish stuff
}
 

injurai

Banned
try/catch/finally?

that more or less inspired my question.

Just i'm not trying something, so I would not need to catch anything. It's more along the lines of because and only because we entered this loop, now I enter the subsequent thing. With the notion that nothing will fail and need to be caught.

The concept of this control structure kind of hit me today, and it seems like it would be too useful not to have already received some sort of implementation. At least in some high level language.
 
do any languages have a logical control that is something like

Code:
while(stuff) {
       //do stuff
} finish {
      //stuff to finish after loop
}

essentially an elegant way of doing one time concluding tasks, like updating a field after building it, or closing buffers. Surprised I have never seen stuff like this.

Wondering because it would make readability in my code a lot better (java/groovy atm)

Don't think so, but there are languages where you can actually create functions like that yourself. Like you create a function that receives another method then do some cleanup. Like python decorators, ruby blocks or javascript functions passed as parameters (basically any language that has first class functions).
 

Slavik81

Member
I'm trying to remember a word I recently used to describe code in which the focus is the result, not the implementation. Such code should be concise, and readable because it doesn't repeat implementation details over and over.

I think the word began with a 'C'. It's driving me mad. Any thoughts?

The word I was looking for was 'expressive'.
 

L034

Member
My brother has one that he uses at a webserver but I don't know what exactly he does with it. I'll ask and report back.

I used it as a public facing webserver with a tiny website, that had 2 visitors at most (including myself) as I had no dynDNS, and so the IP address would change every time my router shutdown :/.

However, for a site with not too many visitors, it'll work.

http://www.dingleberrypi.com/2012/09/tutorial-install-apache-php-and-mysql-on-raspberry-pi/

This tutorial, and the rest of the site are hosted on a pi.
 

Sharp

Member
Used two languages for the first time last week, which is always fun.

Scala (Scalding / Hadoop):
Code:
import com.twitter.scalding._
import scala.util.parsing.json._

class BigDataCount(args : Args) extends Job(args) {
  TextLine( args("input") )
    .map('line -> ('id, 'isBig)) { line : String => countThings(line) }
    .filter('id) { id : Integer => id >= 0 }
    .groupBy('id) { _.max('isBig) }
    .flatMap('isBig -> 'counter) {
      isBig : Boolean => {
        if (isBig) {
          List("any", "big data")
        } else {
          List("any")
        }
      }
    }
    .groupBy('counter) { _.size }
    .write( Tsv( args("output") ) )
  
  def countThings(text : String) : (Integer, Boolean) = {
    var result = JSON.parseFull(text)
    
    result match {
      case Some(map : Map[String, Any]) =>
        (
          map.get("id") match {
            case Some(id : Double) => id.toInt
            case _ => -1
          },
          map.get("product_desc") match {
            case Some(desc : String) => desc.toLowerCase contains "big data"
            case _ => false
          }
        )
      case _ => (-1, false)
    }
  }
}

Prolog (square root function):
Code:
procx((X,Y,R),TopNext) :-
  procx((X,Y),R,(0,0,0),TopNext),
  !.
procx((X,R),TopNext) :-
  !,
  procx((X),R,(0,0,0),TopNext).
procx(X,TopNext) :-
  procx((X),0,0,0,_,_,TopNext).

procx(X,(Y,Z,R),(U,Bot,Top),TopNext) :-
  !,
  procx(X,U,Bot,Top,UNext,BotNext,TopNextTemp),
  procx((Y,Z),R,(UNext,BotNext,TopNextTemp),TopNext).
procx(X,(Y,Z),(U,Bot,Top),TopNext) :-
  !,
  procx(X,U,Bot,Top,UNext,BotNext,TopNextTemp),
  procx(Y,Z,(UNext,BotNext,TopNextTemp),TopNext).
procx((_,_),_,_,_) :-
  !,
  fail.
procx(X,Y,(U,Bot,Top),TopNext) :-
  procx((X,Y),U,Bot,Top,_,_,TopNext).

procx((X,Y),U,Bot,Top,UNext,BotNext,TopNext) :-
  !,
  procx((Bot - U) * 100 + X * 10 + Y,Top,UNext,BotNext,TopNext).
procx((X),U,Bot,Top,UNext,BotNext,TopNext) :-
  procx((Bot - U) * 10 + X,Top,UNext,BotNext,TopNext).

procx(Bot,Top,UNext,BotNext,TopNext) :-
  BotNext is Bot,
  SideNext is 2 * Top,
  between(1,10,VMax),
  (VMax * (SideNext * 10 + VMax) > Bot -> true ; VMax is 10),
  !,
  VNext is VMax - 1,
  UNext is VNext * (SideNext * 10 + VNext),
  TopNext is Top * 10 + VNext.

Functional programming is fun.
 
Correct. If your code only uses standard libraries, it should build without issue in gcc or clang. (If you don't have a preference, use clang.) At most, they might warn you about some things which VS does not notice. Going the other way, developing on gcc or clang and trying to later build with VS doesn't necessarily go as smoothly. VS lacks support for a lot of standard language and library features. Most of that difference should disappear when VS2013 arrives though.
I'm actually doing cross-platform development with VS 2012 and Clang right now and I noticed a feature missing from Clang that worked in VS 2012 (the put_time() function, which is part of the standard library and is still missing from the libstdc++ implementation) Apart from that, Clang as of version 3.3 or so supports all of the C++11 standard and I believe they already started on some of C++14's features.

^^ Yeah, I've started and stopped learning functional programming a few times in the last few years, but I think now it finally clicked with me, mostly because I did the functional programming course with Scala on Coursera. When you port an application over to Scala from C++ and some of the functions are just oneliners instead of 25 lines long, that's pretty awesome.
 

Bollocks

Member
do any languages have a logical control that is something like

Code:
while(stuff) {
       //do stuff
} finish {
      //stuff to finish after loop
}

essentially an elegant way of doing one time concluding tasks, like updating a field after building it, or closing buffers. Surprised I have never seen stuff like this.

Wondering because it would make readability in my code a lot better (java/groovy atm)
What about C# finally statement?
http://msdn.microsoft.com/en-us/library/zwc8s4fz(v=vs.71).aspx
 

Sharp

Member
Maybe the way I got introduced to it was bad, but for me Prolog is hell. I honestly didn't think one time "man, this is easier than in other languages".
It results in really natural representations for a lot of problems in AI. Square root is a really bad example of something to do in Prolog :p
 
Anyone ever work in project management side of things?

I've typically worked in prog/design but a good opportunity has presented itself.

Any tips?
 

Sharp

Member
Not quite what he wants. What he wants is actually really strange. Consider the following C program:

Code:
[b]extern[/b] [b]void[/b] dummy ([b]void[/b]); [i]/* Not defined -- used to force optimizer not to collapse loops, etc. */[/i]

[b]void[/b] main ([b]unsigned[/b] [b]int[/b] argc) { [i]/* We use argc because the optimizer forward propagates constants */[/i]
  [b]if[/b] (argc) {
    [b]while[/b] (argc) {
      --argc;
      dummy ();
    };
    dummy ();
  }
}

Run that through the optimizer on Ubuntu (gcc -S -Os, aka optimizing for binary size, which I did to make sure it didn't duplicate code for speed reasons or anything), and the salient part (the if/loop) look like this:
Code:
        [b]testl[/b]   %ebx, %ebx
        [b]je[/b]      .L1
.L6:
        [b]decl[/b]    %ebx
        [b]call[/b]    dummy
        [b]testl[/b]   %ebx, %ebx
        [b]jne[/b]     .L6
        [b]call[/b]    dummy
.L1:
In other words, when the optimizer doesn't have enough information to use arithmetic tricks, unroll the loop or otherwise cleverly share code (which it is very good at, hence why it took me a while to get this to do what I wanted :p), there have to be at least two comparisons in the resulting binary (or you have to generate a lot more code by putting the comparison in a function, and then you still have two function calls so you haven't really saved anything). They're fundamentally different states. This is as opposed to, e.g., a do-while statement, which can be done as a single comparison quite easily with goto (or other types of local jumps). That, most likely, is why what he's asking for isn't a single control construct in most compiled languages (that I know of, anyway).

The other reason why I think it's not a control structure is that what you're describing (performing cleanup only if a loop is entered) really doesn't make sense most of the time. If there's initialization required it usually has to happen before the loop starts, since if it's in the loop body or comparison statement it is either reinitialized each time through the loop, which means it should be destroyed each time through the loop as well, or you have to do the initialization only conditionally, in which case it's no longer that elegant and is probably slower. There are a *couple* of exceptions I can think of (allocate, do work, if done terminate, otherwise deallocate and continue loop, then at the very end perform some sort of final work on the result and then deallocate), but not many. What's the specific use case you were thinking of for it?
 
Hey guys,

I'm currently writing a game in SFML 2.0 (c++). So far everything is going well but one thing confuses me the most. My game has a bunch of states where something is displayed i.e splash, main menu, stage select, game, etc.

Each state has a loop in which I've thrown a sleep function in there but I'm wondering for how many milliseconds should I sleep my game for during a loop?

I ideally want this game to run at 60 fps max/stable.

Is it normal to have states sleep at a different amount of milliseconds? Or should the whole game be consistent with it's milliseconds of sleeping?

I'm just a bit unsure how to progress with that little topic there.

Thanks!
 

Sharp

Member
Hey guys,

I'm currently writing a game in SFML 2.0 (c++). So far everything is going well but one thing confuses me the most. My game has a bunch of states where something is displayed i.e splash, main menu, stage select, game, etc.

Each state has a loop in which I've thrown a sleep function in there but I'm wondering for how many milliseconds should I sleep my game for during a loop?

I ideally want this game to run at 60 fps max/stable.

Is it normal to have states sleep at a different amount of milliseconds? Or should the whole game be consistent with it's milliseconds of sleeping?

I'm just a bit unsure how to progress with that little topic there.

Thanks!
In general, if you want a smooth framerate you can't use a constant sleep time. You have to determine how long the processing in (e.g.) your rendering loop took, and then sleep for less or more time depending on that. For example, if you wanted 60 frames per second, and rendering took no time at all, you'd want to sleep for 1000 / 60 seconds (call it 17 ms), but if you collected the current time just before you started rendering, and just after, and 10 ms had elapsed, you would only want to sleep for 7 ms. And of course it gets more complicated from there--for example, if the rendering takes longer than 17 ms on some systems, you could choose to just render as fast as possible (inconsistent framerate, but closest to 60 fps), or you might want to make the target framerate configurable, so players with slower machines could experience a smooth framerate of, say, 30 fps (33 ms).

(There are also things like screen tearing and double buffering to consider, since the hardware has its own processes with their own timers... not to mention concerns like your physics loop being out of sync with your main loop, etc. It can get quite complicated to make things really smooth.)
 

injurai

Banned

finally always runs after a try, or try catch block. It is usually handling clean up, or closing out of things that have a potential to fail and through an error.

What I'm talking about doesn't really give new functionality but is a clean way of conveying a certain logical flow of control. Similarly how loops have breaks and continues to cleanly alter a loops functionality in an easily conveyable way, I was hoping while loops might have something similar to my finish suggestion.

while(some case) {
//stuff that potentially happens
} finish {
//stuff that is needed to be done after the loop runs, if and only if the loop was actually entered. also a 1 time sort of thing that doesn't belong in the loop.
}

So that could easily be done with a follow up if statement by setting some Boolean flags or what have you, but that is always unclean in code if you ask me. Guess I should write in good ol' barney and get this added to C++15
 
In general, if you want a smooth framerate you can't use a constant sleep time. You have to determine how long the processing in (e.g.) your rendering loop took, and then sleep for less or more time depending on that. For example, if you wanted 60 frames per second, and rendering took no time at all, you'd want to sleep for 1000 / 60 seconds (call it 17 ms), but if you collected the current time just before you started rendering, and just after, and 10 ms had elapsed, you would only want to sleep for 7 ms. And of course it gets more complicated from there--for example, if the rendering takes longer than 17 ms on some systems, you could choose to just render as fast as possible (inconsistent framerate, but closest to 60 fps), or you might want to make the target framerate configurable, so players with slower machines could experience a smooth framerate of, say, 30 fps (33 ms).

(There are also things like screen tearing and double buffering to consider, since the hardware has its own processes with their own timers... not to mention concerns like your physics loop being out of sync with your main loop, etc. It can get quite complicated to make things really smooth.)

Looks like I have some reading to do. I'm guessing I'll need a class solely dedicated to handling a clock and/or dealing with the framerate stuff.
 

Sharp

Member
finally always runs after a try, or try catch block. It is usually handling clean up, or closing out of things that have a potential to fail and through an error.

What I'm talking about doesn't really give new functionality but is a clean way of conveying a certain logical flow of control. Similarly how loops have breaks and continues to cleanly alter a loops functionality in an easily conveyable way, I was hoping while loops might have something similar to my finish suggestion.



So that could easily be done with a follow up if statement by setting some Boolean flags or what have you, but that is always unclean in code if you ask me. Guess I should write in good ol' barney and get this added to C++15
That's the thing... it's really not fundamentally a clean way of representing local control flow without gotos. It actually requires generating two different comparison statements, one of which is hidden, because there are now two states to deal with--the 'initial comparison' state, and the 'loop comparison' state. Representing that explicitly isn't unclean code :)
Looks like I have some reading to do. I'm guessing I'll need a class solely dedicated to handling a clock and/or dealing with the framerate stuff.
The best way to learn it is probably to read through code in existing games, and just generally gain a lot of experience on working with graphics programming. Because so much of timing is machine-dependent--including, believe it or not, the accuracy of the timer itself :)--the thing you always want to keep in mind is "would this work if my machine were ten times slower (faster) at doing this?" If you keep that in mind and always try to use best practices when interacting with physical machine hardware, you'll be fine.
 

injurai

Banned
That's the thing... it's really not fundamentally a clean way of representing local control flow without gotos. It actually requires generating two different comparison statements, one of which is hidden, because there are now two states to deal with--the 'initial comparison' state, and the 'loop comparison' state. Representing that explicitly isn't unclean code :)

Well we have compilers for a reason. Firstly (atleast in my mind) it makes the source code very clean and conveys exactly it's meaning. Second, it would be a matter of the compiler adding the flags and if structure around the loop, of course this would all cleanly be done in goto statements that we would never have to read.

The mere fact that there would be an extra comparison or states is really a non issue. Its such a small amount of memory on the stack, running in constant time. Not saying they should waste there time adding it, but if they had a magic wand there would be no reason not to wave it.
 

Sharp

Member
Well we have compilers for a reason. Firstly (atleast in my mind) it makes the source code very clean and conveys exactly it's meaning. Second, it would be a matter of the compiler adding the flags and if structure around the loop, of course this would all cleanly be done in goto statements that we would never have to read.

The mere fact that there would be an extra comparison or states is really a non issue. Its such a small amount of memory on the stack, running in constant time. Not saying they should waste there time adding it, but if they had a magic wand there would be no reason not to wave it.
First off, there's such a thing as feature bloat :) I'll ask you again, what would you actually use this for? Like I said in a previous post, it seems to me to be really useful only in very rare circumstances, which is probably why no language that I've used has this feature (that I know of).

Secondly, very few existing control structures or primitives work like this, in C++ or otherwise. The closest one is probably the postfix increment operator (as in x++), which first returns x and then increments, and that behavior is usually considered incredibly confusing--people are warned against using it. Beyond that, it wouldn't just be a constant-time operation--the entire comparison has to be done at least twice, as should be clear if I rewrite the above C program as a do-while (which is basically what the compiler turns it into):
Code:
[b]extern[/b] [b]void[/b] dummy ([b]void[/b]); [i]/* Not defined -- used to force optimizer not to collapse loops, etc. */[/i]

[b]void[/b] main ([b]unsigned[/b] [b]int[/b] argc) { [i]/* We use argc because the optimizer forward propagates constants */[/i]
  [b]if[/b] (argc) {
    [b]do[/b] {
      --argc;
      dummy ();
    } [b]while[/b] (argc);
    dummy ();
  }
}
In this particular case, because we are just using argc for the comparison, it would be a constant-time operation. But if we replaced it with an arbitrary function, that entire function would have to be duplicated. One of the nicer things about C is that code with side effects like turning a single call of a function into two calls is clearly marked (unless you use macros, which you could already use to generate a construct that does what you want here if you were so inclined). C++ strays from this somewhat with things like automatic copy constructors and operator overloading, but again, those are both things that are frowned upon stylistically--and they both have way more practical usecases than what you want to add.

As a bonus, here's your construct as a macro:

Code:
[b]#define[/b] while_finally(x,y,z) [b]if[/b] (x) { [b]do[/b] { y } [b]while[/b] (x); z; }

[b]extern[/b] [b]void[/b] dummy ([b]void[/b]); [i]/* Not defined -- used to force optimizer not to collapse loops, etc. */[/i]

[b]void[/b] main ([b]unsigned[/b] [b]int[/b] argc) { [i]/* We use argc because the optimizer forward propagates constants */[/i]
  while_finally (argc, {
    --argc;
    dummy ();
  }, {
    dummy ();
  })
}
Not only does this accomplish exactly what you wanted the operator to, if you want to you can add an else after the while_finally to execute code only if you never enter the loop.
 

usea

Member
finally always runs after a try, or try catch block. It is usually handling clean up, or closing out of things that have a potential to fail and through an error.

What I'm talking about doesn't really give new functionality but is a clean way of conveying a certain logical flow of control. Similarly how loops have breaks and continues to cleanly alter a loops functionality in an easily conveyable way, I was hoping while loops might have something similar to my finish suggestion.
I disagree. I don't think it's very clear at all how "finish" would behave after a while loop just by looking at it. In fact, most people in the thread were confused even after you explained it.

Running after the loop, but only if the loop executed at least once is pretty weird. Like Sharp said, there's another state in there you have to track. Not just for the computer, but in your mental model of the semantics as well. Also, how would it work with a do while loop? Does it execute every time, or only if the loop body executed at least twice?

What about exceptions? If the main purpose is cleanup code, shouldn't it always be executed like a finally? But that would be even more magic thrown into this operation.
 

injurai

Banned
Ok, both of your points are very good and sound. I still sort of want to defend it, because it makes sense in my mind from a code conveyance stance. But perhaps it shouldn't become standard to any language.

As a bonus, here's your construct as a macro:

Code:
[b]#define[/b] while_finally(x,y,z) [b]if[/b] (x) { [b]do[/b] { y } [b]while[/b] (x); z; }

[b]extern[/b] [b]void[/b] dummy ([b]void[/b]); [i]/* Not defined -- used to force optimizer not to collapse loops, etc. */[/i]

[b]void[/b] main ([b]unsigned[/b] [b]int[/b] argc) { [i]/* We use argc because the optimizer forward propagates constants */[/i]
  while_finally (argc, {
    --argc;
    dummy ();
  }, {
    dummy ();
  })
}
Not only does this accomplish exactly what you wanted the operator to, if you want to you can add an else after the while_finally to execute code only if you never enter the loop.

and thank you, this is neat to see. I've never really looked into doing things like this.
 

Keyouta

Junior Member
So I want to learn C and then C++. I bought 4 books I thought would be good, what does GAF think about them?

The C Programming Language 2nd Edition
C++ Primer Plus 6th Edition
Beginning C++ Through Game Programming 3rd Edition
Accelerated C++
 

Sharp

Member
Ok, both of your points are very good and sound. I still sort of want to defend it, because it makes sense in my mind from a code conveyance stance. But perhaps it shouldn't become standard to any language.



and thank you, this is neat to see. I've never really looked into doing things like this.
Macros are quite powerful. Here's a variant that looks almost exactly like your proposed version (though it can only be called once per function--as far as I can tell, there is no way to quite get NEW_LABEL to do what we want, since even the GNU extensions that allow for declaring local label variables require them to be defined within a block):
Code:
[b]#define[/b] CAT(x, y) x ## y
[b]#define[/b] DEFER_CAT(x, y) CAT (x, y)
[b]#define[/b] NEW_LABEL(label) DEFER_CAT (try_while_, label)
[b]#define[/b] try_while(x) [b]if[/b] (!(x)) [b]goto[/b] NEW_LABEL (3); [b]goto[/b] NEW_LABEL (2); NEW_LABEL (1): [b]if[/b] (x) { NEW_LABEL (2): 
[b]#define[/b] finally [b]goto[/b] NEW_LABEL(1); } [b]if[/b] (0) { NEW_LABEL(3): /* noop */; } [b]else[/b]

[b]extern[/b] [b]void[/b] dummy ([b]void[/b]); [i]/* Not defined -- used to force optimizer not to collapse loops, etc. */[/i]

[b]void[/b] main ([b]unsigned[/b] [b]int[/b] argc) { [i]/* We use argc because the optimizer forward propagates constants */[/i]
  try_while (argc) {
    --argc;
    dummy ();
  } finally {
    dummy ();
  }
}

Doing stuff that way isn't really recommended though :p
 
Top Bottom