I++ vs i+=1


  • FoxDev

    @darkmatter said:

    I mostly just use ternaries for null checks on initializing variables (in certain languages anyway...)

    I tend to use ternaries mainly for choosing between one of two assignments based on a simple condition, except when I can use the null coalescing operator.
    @darkmatter said:
    I begrudgingly use the int? syntax, but don't like it because it looks like Visual Studio is questioning my ability to choose/recognize my own variables' types.

    I used to prefer the Nullable<T> syntax, but T? is just so much easier to type…



  • @accalia said:

    why make the exception for loops?

    for (var i=0; i &lt; 42; i+=1){
        foo(bar, i);
    }
    ```</blockquote>
    
    **tar's posulate:** For any standard idiom that exists in any programming language, there's _always_ someone who thinks that they've managed to come up with a non-idiomatic approach which is somehow 'better' than the established way of doing things.
    
    <small>Filed under: <a>I don't exclude myself from this, either.

  • FoxDev

    preferred style is to use var statements where the use of var does not cause the compiler to autopick an inconventiant type (it will sometimes pick a superclass that is a bit too broad and removes access to an inherited method we want without a cast (or simply not using var in the first place)

    var assignment from method calls is preferred when the type can be reasonably inferred from the name of the method or we don't actually care about the type (we're passing it off unchanged to another method)



  • @Gaska said:

    But C++ fixes its uselessness safety by letting the programmer overload it.

    <empty>


  • @accalia said:

    that's an acceptable solution, although where available it is prefered to use the null coalescing operator (?? in C#)

    I don't think the null-coalescing op works in scenarios like the one detailed by @darkmatter.



  • @accalia said:

    my initial preferences, yes. but over the years the style has been altered with many suggestions from other developers. barely a quarter of the original rules are still in place unaltered, and fully half of them are completely changed now.

    as for the idiomatic short form... I'll be honest it is not the short form itself i'm attempting to ban. it's the inline use of it. If i found a linter that was able to discriminate between pre/postincerment as a statement and in an expression i'd lift the ban.

    see my original example: example 1 would be allowed if the sylechecker could discriminate it from example 2. i haven't found any such stylechecker and because stylechecks are completely automated (so code reviews can focus on algorythms and correctness and not style) that means that both forms are not allwoed.

    I agree your first example was an awful use of ++. But that's a behavior/training problem, not a language problem. Your approach seems like burning down the business to enforce the no shirt-no service policy.



  • @blakeyrat said:

    I would argue that in a proper strongly-typed language, a integer used solely for indexing an array would not be the same type as an integer storing business-logic data. And attempting to mix them would throw an error.

    I suppose something like:

    struct BusinessInt {
        int value;
    };
    
    void do_business_stuff(BusinessInt i) { /*...*/ }
    

    Might give you maybe 80-90% of what you want...



  • @abarker said:

    I don't think the null-coalescing op works in scenarios like the one detailed by @darkmatter.

    You are correct. ?? is nice in situations where it's usable, which is almost never in my experience.


  • FoxDev

    @abarker said:

    I don't think the null-coalescing op works in scenarios like the one detailed by @darkmatter.

    true, but i did say where available.


  • FoxDev

    @fwd said:

    I agree your first example was an awful use of ++. But that's a behavior/training problem, not a language problem. Your approach seems like burning down the business to enforce the no shirt-no service policy.

    Is it though?

    yes the first example is terrible and it is a training issue, but when you have all style checks automated, it is unfortunate that you lose theability to use ++ and -- where the use is okay, but in every one of those places += and -= work as well.

    Additionally by automating style checks (and forcing unit test to pass) before accepting checkins for code review a lot of time is saved by allowing the code review to focus on algorithms and correctness rather than style and making sure test cases pass.

    given that this is an overall time saver for every developer, i fail to see how that could be an overall bad thing. Yes i would like to remove that ban, and i have been asked to many times, but until the proper checking can be enforced automatically i leave it in, because otherwise i lose the benefit of having the style guidelines enforced automatically


  • BINNED

    @accalia said:

    var q = (++i + 4) * (i++-1);

    I'm no C expert, but are the results of that even defined in the spec?

    @accalia said:

    so i forbid ++ and -- in projects i have control over. it's not that big a deal and it means you can't pull that shite on me.

    Or if you wanted to take that way too far, you could force them to use Ada. 😄

    @RaceProUK said:

    Is that a @ben_lubar I hear approaching…

    It is @ben_lubar that uses a language like that, isn't it?

    Perhaps you were thinking of Sir @antiquarian of the Static Typing Brigade? bows and flourishes hat

    @FrostCat said:

    Ada, where you'd declare a new int type for your loop counter.

    Even I think that's taking things too far. One int type for all loop counters will suffice. I may be joking about this; I'm not sure.


  • FoxDev

    @antiquarian said:

    Perhaps you were thinking of Sir @antiquarian of the Static Typing Brigade? bows and flourishes hat

    It was one of you two, I know that. Or maybe both.
    Also, you're currently hatless; how can you flourish that wish you do not have? 😛


  • :belt_onion:

    It's especially glaring when you practice methods of writing code that looks like plain sentences....
    [code]
    if(DoingTheThingWorks())
    {
    bool? isItOne = myValueFromInput == HARDWIRED_DEFAULT_BUT_SUBJECT_TO_CHANGE_VALUE_THAT_EQUALS_AIRQUOTES_ONE;
    }

    [/code]
    Is it a bool?? IS IT?!?!

    @RaceProUK said:

    but T? is just so much easier to type…

    Moar questionmarksssss ❓ ❔

    [code]
    int? i=++i==j--?o:O;
    [/code]

    @abarker said:

    I don't think the null-coalescing op works in scenarios like the one detailed by @darkmatter.

    Correct, the error in my example is an array index out of bounds style error, not a you stored a null value in a non-nullable primitive error.



  • @Jarry said:

    cluebating

    cluebait:

    • *(v)* — To post known invalid information in an attempt to provoke a correction.
    • *(n)* — data posted as a cluebaiting attempt.

  • FoxDev

    @antiquarian said:

    I'm no C expert, but are the results of that even defined in the spec?

    it isn't. however both GCC and CLANG produce the naively expected results. no idea about mingw or VC++



  • @accalia said:

    Is it though?

    yes the first example is terrible and it is a training issue, but when you have all style checks automated, it is unfortunate that you lose theability to use ++ and -- where the use is okay, but in every one of those places += and -= work as well.

    Additionally by automating style checks (and forcing unit test to pass) before accepting checkins for code review a lot of time is saved by allowing the code review to focus on algorithms and correctness rather than style and making sure test cases pass.

    given that this is an overall time saver for every developer, i fail to see how that could be an overall bad thing. Yes i would like to remove that ban, and i have been asked to many times, but until the proper checking can be enforced automatically i leave it in, because otherwise i lose the benefit of having the style guidelines enforced automatically

    Only if they are dumb enough to try something ala your example in the first place. For everyone else that knows better, you don't gain anything and you annoy them. Having to do something the "wrong" way because of some automated test babysitting dummies is insulting, having to alter every for loop I have the IDE autocomplete for me would be hassle, and seeing the +=1 littered throughout the code would be annoying to the point of distraction. Hence the resentment point above.

    And really, if you have a developer writing something like your example on purpose, I'd want to know about. Because god knows what other crazy shit they are trying to pull that your automated tests aren't tuned for.


  • BINNED

    @accalia said:

    so i+=1 is cleaner and i++ is dirtier

    Gah, I hate operators crammed onto the operands. I always write stuff like that as i += 1;

    ++i; I have no objections to though. I guess it's because it's only one operand?

    Yes, I'm weird. What of it?



  • @fwd said:

    it's super grating having to go back and rewrite perfectly good code to fit someone's personal whims.

    If you've written code which conforms to the coding standard, and it passes all the tests, I don't see why anyone should be able to demand changes to it.

    (Then there's those asshole developers who claim that they can't even read code if it has the "wrong" bracing style of whatever, but personally I think those people should be shunned and have all their checkins autoreverted by a commit hook...)


  • ♿ (Parody)

    @Onyx said:

    Gah, I hate operators crammed onto the operands. I always write stuff like that as i += 1;

    Yes! Spaces, people! Use them! Also, exclamation points!


  • :belt_onion:

    Tried to click the notification to see which post @accalia likes and it takes me here...
    note that everything in the picture indicates I'm at post 98... the URL at the top, the link text at the bottom, even the lametacular green postcounterwidget.

    But is it? Is it REALLY?

    Tried clicking it multiple times, tried navigating away and then clicking back to it... nothing fixes that one for me.


  • :belt_onion:

    @darkmatter said:

    Tried clicking it multiple times, tried navigating away and then clicking back to it... nothing fixes that one for me.

    Finally got there, had to reload duckwhores.


  • BINNED

    @abarker said:

    ternary operators

    Those things are damned useful at times.

    $var = isset($_GET['arg']) ? $_GET['arg'] ? ARG_DEFAULT;
    

    If not for ternaries some of my files would be almost double the length just because of shit like this.

    Also, what @darkmatter posted somewhere above



  • cannot use y (type int) as type BusinessInt in assignment


  • Discourse touched me in a no-no place

    @accalia said:

    i'm not a fan of [ternaries].

    What about trigraphs?


  • BINNED

    @darkmatter said:

    duckwhores

    Howard the Duck Tits Picture (NSFW)

    Note to self: use private windows more. You didn't really need "howard the duck tits" as a search term Google will associate with you in the future...



  • @tar said:

    If you've written code which conforms to the coding standard, and it passes all the tests, I don't see why anyone should be able to demand changes to it.

    (Then there's those asshole developers who claim that they can't even read code if it has the "wrong" bracing style of whatever, but personally I think those people should be shunned and have all their checkins autoreverted by a commit hook...)

    Our coding standards are pretty light and mostly cover naming conventions for variables, tables, etc. I don't want to be one of "those" guys and I don't think I am, but I do have a hard time reading large blocks of code with insufficient whitespace. This has been where most of my conflicts arise, where I'm told to cut blank lines and spaces to reduce the vertical height of the code. The fact that we have chunks of code that long should probably indicate we should have a discussion about it, but that's for another day.


  • Discourse touched me in a no-no place

    @Onyx said:

    You didn't really need "howard the duck tits" as a search term Google will associate with you in the future...

    Yes you did.


  • FoxDev

    @Onyx said:

    @abarker said:
    ternary operators

    Those things are damned useful at times.

    $var = isset($_GET['arg']) ? $_GET['arg'] ? ARG_DEFAULT;
    ```</blockquote>
    Another example (from memory, so not 100%):
    ```csharp
    transaction.TransactionType = InvoiceType == InvoiceType.Credit ? TransactionType.CustomerRefund : TransactionType.CustomerReceipt;
    


  • @ben_lubar said:

    Why doesn't std::array special-case bool like std::vector does?

    Becasuse std::vector<bool> was a mistake?


  • BINNED

    @fwd said:

    blank lines

    Before if statements and loops, and after closed blocks, please.

    Also, after variable declarations if you wouldn't mind. Though I can be more lenient with those.



  • What if I have an array of bools and I want to use them in a space-efficient way?


  • Java Dev

    I like clear, concise code. For that reason, I may write fragments like *s++ = 'x', or array[i++] = foo. Especially if I'm using the same left-hand side in a number of subsequent statements. Deal with it.


  • FoxDev

    @fwd said:

    Having to do something the "wrong" way because of some automated test babysitting dummies is insulting

    hmm... Well youoare certainly welcome to your opinion there, but i've been burned too many times by not having those automated babysitters in place, by old and new developers, good and bad developers as well. I'm keeping those "babysitters" in place because with them in place i know damn well that:

    1. i'm not regressing bugs
    2. I don't have to worry about unexpected side effects
    3. i am very unlikely to accidentally trigger undefined behaviour
    4. my code looks like everyone else's for this project so no one has to context switch between styles.


  • s = append(s, 'x')
    array = append(array, foo)
    

    Pointer arithmetic (yes, even including array[i++]) is naughty.



  • @fwd said:

    You are correct. ?? is nice in situations where it's usable, which is almost never in my experience.

    I wish there was a ??. null-safe scope resolution operator, which returned null if the LHS is null. Like Haskell's Maybe<T>.

    @ben_lubar said:

    What if I have an array of bools and I want to use them in a space-efficient way?

    @ben_lubar said:
    Pointer arithmetic (yes, even including array[i++]) is naughty.

    You don't want an array or a std::array, you want a bitfield.


  • :belt_onion:

    @ben_lubar said:

    What if I have an array of bools and I want to use them in a space-efficient way?

    Then you probably wouldn't have used crappy username join methods.


  • Java Dev

    @ben_lubar said:

    ```go
    s = append(s, 'x')
    array = append(array, foo)

    
    Pointer arithmetic (yes, even including `array[i++]`) is naughty.</blockquote>
    
    I don't write go.

  • Discourse touched me in a no-no place

    @accalia said:

    i forbid ++ and -- in projects i have control over

    You should forbid += and -= too; after all, i=i+1 is only one character longer than i+=1, and that'll force everyone to say what they mean.


  • FoxDev

    @dkf said:

    You should forbid += and -= too; after all, i=i+1 is only one character longer than i+=1, and that'll force everyone to say what they mean.

    i+=1 and i-=1 are atomic, i=i+1 and i=i-1 are not (in C# at least)


  • Discourse touched me in a no-no place

    @RaceProUK said:

    i+=1 and i-=1 are atomic, i=i+1 and i=i-1 are not (in C# at least)

    You can also use them multiple times in the same statement without worrying about sequence points in C# (and Java too) as that's got defined evaluation order for things like that; the semantics are well-defined and the compiler's just got to figure out what to do with it. Unlike in C and C++…

    In fact, virtually this whole thread counts as idiotic in any language other than C or C++ and I've spent far too long reading it.


  • FoxDev

    @dkf said:

    I've spent far too long reading it.

    At least it'll help towards the reader badges ;)



  • @dkf said:

    i=i+1

    That's probably still a little bit obfuscated, don't you think? Better to abstract it away with a function so the intent is clear:

    const int DEFAULT_INCREMENT = 1;
    
    void increment_integer_value(int &i) {
        i = i + DEFAULT_INCREMENT;
    }
    

    Now it's nice and straightforward, and this way, if we decide that we want to start incrementing by, say 2 instead of 1, we only need to change the code in one place.



  • @accalia said:

    var q = (++i + 4) * (i++-1);

    I'd totally write that as var q = ((i+=1) + 4) * (-2 + (i+=1)) and pass @accalia's code review! :trollface:


  • :belt_onion:

    @PleegWat said:

    Pointer arithmetic (yes, even including array[i++]) is naughty.

    [code]
    char* o(char* i,char[] a)
    {

     char **p = &a[--i>=(char*)0x00FFFFFF?o(i,a):i];
     return *p;
    

    }
    [/code]
    or something :trollface:

    @RaceProUK said:

    i+=1 and i-=1 are atomic

    So is Potassium but you don't see my code littered with that or Franciniums or Cobalts :rimshot:



  • NEEDS_XML
    and dependency injection. what if we decide to change the int class?


  • Java Dev

    That's a misattribution.


  • FoxDev

    @dkf said:

    You should forbid += and -= too; after all, i=i+1 is only one character longer than i+=1, and that'll force everyone to say what they mean.

    atomic operations.

    i+=x is atomic.

    i = i + x isn't


  • FoxDev

    -_-

    well then..... i can see we have a troublemaker on our hands



  • @accalia said:

    -_-

    well then..... i can see we have a troublemaker on our hands

    ... and here I was hoping that += would be banned too. 😞

    Filed under: var q = ((i=+1+i) + 4) * (-2 + (i=+i+1))


  • FoxDev

    if i banned all shortcut operators i'd have a riot on my hands. only banning ++ and -- i just have grumbling and occasional arguments.


Log in to reply