What's a good pattern to calculate a variable only when it is used the first time?boost::trim each string in std::vector<std::string>Pretty-print C++ STL containersIs it bad design for a class to give access to its data (via ptr/it) when this data can be deleted before the class object is out of scope?How to quickly concatenate char arrays?No python class registered for C++ class function pointerfull template specialization not working: no instance of function template “mysort2” matches the specified type STLTestsZeroMQ (cppzmq) subscriber skips first messageCan replacing the std::allocator allow std::set to work with void* and separate copy/dealloc functions?Returning string constants in switch-case block with std::string

Graphs for which a calculus student can reasonably compute the arclength

What is the prop for Thor's hammer (Mjölnir) made of?

What should we do with manuals from the 80s?

What is the proper name for a circle with a line through it?

Escape Velocity - Won't the orbital path just become larger with higher initial velocity?

Attacking the Hydra

Telephone number in spoken words

Good textbook for queueing theory and performance modeling

Is there a name for the technique in songs/poems, where the rhyming pattern primes the listener for a certain line, which never comes?

What would it take to get a message to another star?

What is the most difficult concept to grasp in Calculus 1?

Scam? Phone call from "Department of Social Security" asking me to call back

Why do my bicycle brakes get worse and feel more 'squishy" over time?

Did Michelle Obama have a staff of 23; and Melania have a staff of 4?

Number in overlapping range

Are there liquid fueled rocket boosters having coaxial fuel/oxidizer tanks?

The more + the + comparative degree

What is the hottest thing in the universe?

Who is the controller of a Pacifism enchanting my creature?

Can anybody tell me who this Pokemon is?

Sum Square Difference, which way is more Pythonic?

What unique challenges/limitations will I face if I start a career as a pilot at 45 years old?

What modifiers are added to the attack and damage rolls of this unique longbow from Waterdeep: Dragon Heist?

Weird resistor with dots around it



What's a good pattern to calculate a variable only when it is used the first time?


boost::trim each string in std::vector<std::string>Pretty-print C++ STL containersIs it bad design for a class to give access to its data (via ptr/it) when this data can be deleted before the class object is out of scope?How to quickly concatenate char arrays?No python class registered for C++ class function pointerfull template specialization not working: no instance of function template “mysort2” matches the specified type STLTestsZeroMQ (cppzmq) subscriber skips first messageCan replacing the std::allocator allow std::set to work with void* and separate copy/dealloc functions?Returning string constants in switch-case block with std::string






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








6















Not an actual problem but I'm looking for a pattern to improve the following logic:



void PrintToGameMasters()

std::string message = GetComplicatedDebugMessage(); // This will create a big string with various info
for (Player* player : GetAllPlayers())
if (player->IsGameMaster())
player->SendMessage(message);



Now this code works, but the issue I have is that in most case there isn't any gamemasters so the message composition will be done for nothing.

I'd like to write something that would only create the message on the first use of that variable, but I can't come up with a good solution here.



EDIT:
To make this question more precise, I'm looking for a solution that's not specific to strings, it could be a type without a function to test if it's initialized.
Also big bonus point if we can keep the call to GetComplicatedDebugMessage at the top of the loop, I think a solution involving a wrapper would solve this.










share|improve this question





















  • 1





    "Also big bonus point if we can keep the call to GetComplicatedDebugMessage at the top of the loop" - why? Then you are right back to initializing the message even if there are no game masters in the list. If it really is so complicated to create the message, why not do so the first time SendMessage(message) is actually called?

    – Remy Lebeau
    7 hours ago


















6















Not an actual problem but I'm looking for a pattern to improve the following logic:



void PrintToGameMasters()

std::string message = GetComplicatedDebugMessage(); // This will create a big string with various info
for (Player* player : GetAllPlayers())
if (player->IsGameMaster())
player->SendMessage(message);



Now this code works, but the issue I have is that in most case there isn't any gamemasters so the message composition will be done for nothing.

I'd like to write something that would only create the message on the first use of that variable, but I can't come up with a good solution here.



EDIT:
To make this question more precise, I'm looking for a solution that's not specific to strings, it could be a type without a function to test if it's initialized.
Also big bonus point if we can keep the call to GetComplicatedDebugMessage at the top of the loop, I think a solution involving a wrapper would solve this.










share|improve this question





















  • 1





    "Also big bonus point if we can keep the call to GetComplicatedDebugMessage at the top of the loop" - why? Then you are right back to initializing the message even if there are no game masters in the list. If it really is so complicated to create the message, why not do so the first time SendMessage(message) is actually called?

    – Remy Lebeau
    7 hours ago














6












6








6


2






Not an actual problem but I'm looking for a pattern to improve the following logic:



void PrintToGameMasters()

std::string message = GetComplicatedDebugMessage(); // This will create a big string with various info
for (Player* player : GetAllPlayers())
if (player->IsGameMaster())
player->SendMessage(message);



Now this code works, but the issue I have is that in most case there isn't any gamemasters so the message composition will be done for nothing.

I'd like to write something that would only create the message on the first use of that variable, but I can't come up with a good solution here.



EDIT:
To make this question more precise, I'm looking for a solution that's not specific to strings, it could be a type without a function to test if it's initialized.
Also big bonus point if we can keep the call to GetComplicatedDebugMessage at the top of the loop, I think a solution involving a wrapper would solve this.










share|improve this question
















Not an actual problem but I'm looking for a pattern to improve the following logic:



void PrintToGameMasters()

std::string message = GetComplicatedDebugMessage(); // This will create a big string with various info
for (Player* player : GetAllPlayers())
if (player->IsGameMaster())
player->SendMessage(message);



Now this code works, but the issue I have is that in most case there isn't any gamemasters so the message composition will be done for nothing.

I'd like to write something that would only create the message on the first use of that variable, but I can't come up with a good solution here.



EDIT:
To make this question more precise, I'm looking for a solution that's not specific to strings, it could be a type without a function to test if it's initialized.
Also big bonus point if we can keep the call to GetComplicatedDebugMessage at the top of the loop, I think a solution involving a wrapper would solve this.







c++






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 8 hours ago







Kelno

















asked 9 hours ago









KelnoKelno

385 bronze badges




385 bronze badges










  • 1





    "Also big bonus point if we can keep the call to GetComplicatedDebugMessage at the top of the loop" - why? Then you are right back to initializing the message even if there are no game masters in the list. If it really is so complicated to create the message, why not do so the first time SendMessage(message) is actually called?

    – Remy Lebeau
    7 hours ago













  • 1





    "Also big bonus point if we can keep the call to GetComplicatedDebugMessage at the top of the loop" - why? Then you are right back to initializing the message even if there are no game masters in the list. If it really is so complicated to create the message, why not do so the first time SendMessage(message) is actually called?

    – Remy Lebeau
    7 hours ago








1




1





"Also big bonus point if we can keep the call to GetComplicatedDebugMessage at the top of the loop" - why? Then you are right back to initializing the message even if there are no game masters in the list. If it really is so complicated to create the message, why not do so the first time SendMessage(message) is actually called?

– Remy Lebeau
7 hours ago






"Also big bonus point if we can keep the call to GetComplicatedDebugMessage at the top of the loop" - why? Then you are right back to initializing the message even if there are no game masters in the list. If it really is so complicated to create the message, why not do so the first time SendMessage(message) is actually called?

– Remy Lebeau
7 hours ago













8 Answers
8






active

oldest

votes


















15














You can use std::call_once with a lambda to call the function the first time you find a game master like



void PrintToGameMasters()

std::once_flag of;
std::string message;
for (Player* player : GetAllPlayers())
if (player->IsGameMaster())

std::call_once(of, [&]() message = GetComplicatedDebugMessage(); );
player->SendMessage(message);







share|improve this answer




















  • 1





    I like this a lot - good use of the C++ Standard Library. Have an upvote!

    – Bathsheba
    9 hours ago






  • 8





    I like it too, but this mechanism is specifically designed to handle the problem of concurrency (e.g.: making sure multiple threads only call something once). As in...it comes with the overhead of an interlock (which could still be very small overhead, but non-zero cost). Whereas a cheap alternative to call_once that was not designed to handle concurrency would simply be a bool where the once_flag is, and the construct of if(!hasBeenCalled) hasBeenCalled=true; fn(); <-- That's all you need. But std::call_once is too convenient to pass up. Just be aware about what it's for.

    – Wyck
    9 hours ago







  • 1





    @Wyck Totaly agree. I just wanted to show it off. Lightness Races in Orbit's answer is the best for efficiency.

    – NathanOliver
    9 hours ago






  • 1





    Nice! That's the kind of answer I was hoping for. It seems it doesn't fit as a generic solution to always reuse because of the lock overhead, but it's very nice to know.

    – Kelno
    8 hours ago


















12














Some good ideas here, but I like to keep it a bit more simple:



void PrintToGameMasters()

std::string message;

for (Player* player : GetAllPlayers())

if (player->IsGameMaster())

if (message.empty())
message = GetComplicatedDebugMessage();

player->SendMessage(message);





Everybody can follow this, and it's cheap as chips… plus it's easy as pie to debug.






share|improve this answer




















  • 2





    Probably suitable for this case. But in general, what if message happens to be empty but still expensive to calculate?

    – sebrockm
    9 hours ago






  • 1





    @sebrockm Then you can introduce a bool hasMessage instead. Either way it's pretty trivial logic.

    – Lightness Races in Orbit
    9 hours ago












  • I do know it's trivial :) but then the entire question is trivial, yet OP asked it. So maybe it's not trivial for them :)

    – sebrockm
    9 hours ago






  • 2





    This is both short and simple. + vote for recognizing when not to use "cool" stuff

    – user1316208
    8 hours ago











  • This would perfectly do in this specific example, as well as the "hasMessage" for non-basic types cases, but I'm trying to find shorter pattern I can reuse, probably a wrapper around the message that would avoid the code clutter.

    – Kelno
    8 hours ago


















4














Wrap the message in a mutable lambda:



auto makeMessage = [message = std::string()]() mutable -> std::string&

if (message.empty())
message = GetComplicatedDebugMessage();

return message;
;

for (Player* player : GetAllPlayers())
if (player->IsGameMaster())
player->SendMessage(makeMessage());





share|improve this answer



























  • I like this one especially, I can make some more generic wrapper out of this easily.

    – Kelno
    8 hours ago












  • @Kelno And the boolean was useless anyway, since you can just check with empty().

    – Nikos C.
    7 hours ago


















3














Use data-oriented design; keep two lists of players: game masters and non-game masters.



void PrintToGameMasters()

auto players = GetGameMasters(); // Returns ONLY game master players
if (players.begin() != players.end())
std::string message = GetComplicatedDebugMessage();
for (Player* player : players)
player->SendMessage(message);





The goal is to minimize if-statements inside loops.




P.S. Since you're developing a game, I want to add this link to Mike Acton's cppcon talk which you might find interesting.






share|improve this answer



























  • I like this a lot.

    – Lightness Races in Orbit
    52 mins ago


















2














Whereas std::string has empty value which might mean "not computed", you might use more generally std::optional which handle empty string and non default constructible types:



void PrintToGameMasters()

std::optional<std::string> message;

for (Player* player : GetAllPlayers())

if (player->IsGameMaster())

if (!message)
message = GetComplicatedDebugMessage();

player->SendMessage(*message);








share|improve this answer

























  • This is good. It removes the reliance on "empty == not calculated yet" with absolutely no source code lines overhead. 👍

    – Lightness Races in Orbit
    50 mins ago











  • In fact, sod it, this is what I'd do.

    – Lightness Races in Orbit
    50 mins ago


















1














Not sure if this is the best pattern, but you can delay computation with a lambda:



void PrintToGameMasters()

std::string message = "";
auto getDebugMessage = [&message]() -> const std::string&
if (message.empty())
message = GetComplicatedDebugMessage();

return message;
;

for (Player* player : GetAllPlayers())
if (player->IsGameMaster())
player->SendMessage(getDebugMessage());






share|improve this answer



























  • getDebug/getMessage

    – Lightness Races in Orbit
    9 hours ago






  • 1





    This also doesn't assign to message on the first call so message is always empty.

    – NathanOliver
    9 hours ago











  • Indeed. Needs to assign in the conditionals, then return message unconditionally. Add a reference return type too (I think?)

    – Lightness Races in Orbit
    9 hours ago











  • @LightnessRacesinOrbit Defenitly needs to return by reference or it defeats the point.

    – NathanOliver
    9 hours ago











  • What I mean is there may be some other "clever" antics that can achieve the same goal while keeping the RT deduction (return (message) or some nonsense like that?) but I deliberately don't bother keeping track of all the various decltype monostrosities because I value my sanity (slightly)!

    – Lightness Races in Orbit
    9 hours ago



















0














Another simplistic approach using static keyword:



void PrintToGameMasters()

for (Player* player : GetAllPlayers())
if (player->IsGameMaster())

static std::string message = GetComplicatedDebugMessage();
player->SendMessage(message);







share|improve this answer



























  • @RemyLebeau: Thanks again, how is the code now?

    – seccpur
    7 hours ago






  • 1





    Do note that this means the string will always be the same. If GetComplicatedDebugMessage() can change it's return value in between calls to PrintToGameMasters() then you won't pick up on that.

    – NathanOliver
    6 hours ago



















0














Really hope this helps



Try maybe implement this logic:



#include <iostream>

using namespace std;

int main()

bool GameMaster,first_time,used_before;

GameMaster = true;
first_time = false;
used_before = false;

GameMaster = first_time;
first_time = used_before;


for( int i = 0; i < 5; i++ )

if(GameMaster==used_before)
cout<<" First Time";
GameMaster = true;


if(GameMaster!=used_before)
cout<<" Old News";



return 0;



With Response:



 First Time Old News Old News Old News Old News Old News 





share|improve this answer



























  • FWIW i = i + 1 can be replaced by ++i, if(GameMaster!=used_before) can be replaced by else, You can also get rid of two of the three bool's as you only need one flag to know if one thing has been done.

    – NathanOliver
    8 hours ago







  • 1





    This is absolutely bizarre code!! Why do you have THREE bool variable when only ONE is actually really used? "used_before" is assigned false at initialisation then never changed! "first_time" is assigned false and then re-assigned "used_before" which is also ALWAYS false! And then, neither "first_time" nor "used_before" are ever given other values in the loop!

    – Adrian
    8 hours ago











  • I didn't say im expert, I was trying to pass variable values, without affecting the previous one. I used this logic before for button polling and it did the job, I didn't consider that bc he only needs to read the change once, 3 variables are overkill. Looks like it could have been done easier, thank you for your suggestions.

    – Andrei Elekes
    2 hours ago











  • Dunno, seems too wordy. Also fix your indentation!!

    – Lightness Races in Orbit
    51 mins ago














Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57510792%2fwhats-a-good-pattern-to-calculate-a-variable-only-when-it-is-used-the-first-tim%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























8 Answers
8






active

oldest

votes








8 Answers
8






active

oldest

votes









active

oldest

votes






active

oldest

votes









15














You can use std::call_once with a lambda to call the function the first time you find a game master like



void PrintToGameMasters()

std::once_flag of;
std::string message;
for (Player* player : GetAllPlayers())
if (player->IsGameMaster())

std::call_once(of, [&]() message = GetComplicatedDebugMessage(); );
player->SendMessage(message);







share|improve this answer




















  • 1





    I like this a lot - good use of the C++ Standard Library. Have an upvote!

    – Bathsheba
    9 hours ago






  • 8





    I like it too, but this mechanism is specifically designed to handle the problem of concurrency (e.g.: making sure multiple threads only call something once). As in...it comes with the overhead of an interlock (which could still be very small overhead, but non-zero cost). Whereas a cheap alternative to call_once that was not designed to handle concurrency would simply be a bool where the once_flag is, and the construct of if(!hasBeenCalled) hasBeenCalled=true; fn(); <-- That's all you need. But std::call_once is too convenient to pass up. Just be aware about what it's for.

    – Wyck
    9 hours ago







  • 1





    @Wyck Totaly agree. I just wanted to show it off. Lightness Races in Orbit's answer is the best for efficiency.

    – NathanOliver
    9 hours ago






  • 1





    Nice! That's the kind of answer I was hoping for. It seems it doesn't fit as a generic solution to always reuse because of the lock overhead, but it's very nice to know.

    – Kelno
    8 hours ago















15














You can use std::call_once with a lambda to call the function the first time you find a game master like



void PrintToGameMasters()

std::once_flag of;
std::string message;
for (Player* player : GetAllPlayers())
if (player->IsGameMaster())

std::call_once(of, [&]() message = GetComplicatedDebugMessage(); );
player->SendMessage(message);







share|improve this answer




















  • 1





    I like this a lot - good use of the C++ Standard Library. Have an upvote!

    – Bathsheba
    9 hours ago






  • 8





    I like it too, but this mechanism is specifically designed to handle the problem of concurrency (e.g.: making sure multiple threads only call something once). As in...it comes with the overhead of an interlock (which could still be very small overhead, but non-zero cost). Whereas a cheap alternative to call_once that was not designed to handle concurrency would simply be a bool where the once_flag is, and the construct of if(!hasBeenCalled) hasBeenCalled=true; fn(); <-- That's all you need. But std::call_once is too convenient to pass up. Just be aware about what it's for.

    – Wyck
    9 hours ago







  • 1





    @Wyck Totaly agree. I just wanted to show it off. Lightness Races in Orbit's answer is the best for efficiency.

    – NathanOliver
    9 hours ago






  • 1





    Nice! That's the kind of answer I was hoping for. It seems it doesn't fit as a generic solution to always reuse because of the lock overhead, but it's very nice to know.

    – Kelno
    8 hours ago













15












15








15







You can use std::call_once with a lambda to call the function the first time you find a game master like



void PrintToGameMasters()

std::once_flag of;
std::string message;
for (Player* player : GetAllPlayers())
if (player->IsGameMaster())

std::call_once(of, [&]() message = GetComplicatedDebugMessage(); );
player->SendMessage(message);







share|improve this answer













You can use std::call_once with a lambda to call the function the first time you find a game master like



void PrintToGameMasters()

std::once_flag of;
std::string message;
for (Player* player : GetAllPlayers())
if (player->IsGameMaster())

std::call_once(of, [&]() message = GetComplicatedDebugMessage(); );
player->SendMessage(message);








share|improve this answer












share|improve this answer



share|improve this answer










answered 9 hours ago









NathanOliverNathanOliver

112k19 gold badges176 silver badges255 bronze badges




112k19 gold badges176 silver badges255 bronze badges










  • 1





    I like this a lot - good use of the C++ Standard Library. Have an upvote!

    – Bathsheba
    9 hours ago






  • 8





    I like it too, but this mechanism is specifically designed to handle the problem of concurrency (e.g.: making sure multiple threads only call something once). As in...it comes with the overhead of an interlock (which could still be very small overhead, but non-zero cost). Whereas a cheap alternative to call_once that was not designed to handle concurrency would simply be a bool where the once_flag is, and the construct of if(!hasBeenCalled) hasBeenCalled=true; fn(); <-- That's all you need. But std::call_once is too convenient to pass up. Just be aware about what it's for.

    – Wyck
    9 hours ago







  • 1





    @Wyck Totaly agree. I just wanted to show it off. Lightness Races in Orbit's answer is the best for efficiency.

    – NathanOliver
    9 hours ago






  • 1





    Nice! That's the kind of answer I was hoping for. It seems it doesn't fit as a generic solution to always reuse because of the lock overhead, but it's very nice to know.

    – Kelno
    8 hours ago












  • 1





    I like this a lot - good use of the C++ Standard Library. Have an upvote!

    – Bathsheba
    9 hours ago






  • 8





    I like it too, but this mechanism is specifically designed to handle the problem of concurrency (e.g.: making sure multiple threads only call something once). As in...it comes with the overhead of an interlock (which could still be very small overhead, but non-zero cost). Whereas a cheap alternative to call_once that was not designed to handle concurrency would simply be a bool where the once_flag is, and the construct of if(!hasBeenCalled) hasBeenCalled=true; fn(); <-- That's all you need. But std::call_once is too convenient to pass up. Just be aware about what it's for.

    – Wyck
    9 hours ago







  • 1





    @Wyck Totaly agree. I just wanted to show it off. Lightness Races in Orbit's answer is the best for efficiency.

    – NathanOliver
    9 hours ago






  • 1





    Nice! That's the kind of answer I was hoping for. It seems it doesn't fit as a generic solution to always reuse because of the lock overhead, but it's very nice to know.

    – Kelno
    8 hours ago







1




1





I like this a lot - good use of the C++ Standard Library. Have an upvote!

– Bathsheba
9 hours ago





I like this a lot - good use of the C++ Standard Library. Have an upvote!

– Bathsheba
9 hours ago




8




8





I like it too, but this mechanism is specifically designed to handle the problem of concurrency (e.g.: making sure multiple threads only call something once). As in...it comes with the overhead of an interlock (which could still be very small overhead, but non-zero cost). Whereas a cheap alternative to call_once that was not designed to handle concurrency would simply be a bool where the once_flag is, and the construct of if(!hasBeenCalled) hasBeenCalled=true; fn(); <-- That's all you need. But std::call_once is too convenient to pass up. Just be aware about what it's for.

– Wyck
9 hours ago






I like it too, but this mechanism is specifically designed to handle the problem of concurrency (e.g.: making sure multiple threads only call something once). As in...it comes with the overhead of an interlock (which could still be very small overhead, but non-zero cost). Whereas a cheap alternative to call_once that was not designed to handle concurrency would simply be a bool where the once_flag is, and the construct of if(!hasBeenCalled) hasBeenCalled=true; fn(); <-- That's all you need. But std::call_once is too convenient to pass up. Just be aware about what it's for.

– Wyck
9 hours ago





1




1





@Wyck Totaly agree. I just wanted to show it off. Lightness Races in Orbit's answer is the best for efficiency.

– NathanOliver
9 hours ago





@Wyck Totaly agree. I just wanted to show it off. Lightness Races in Orbit's answer is the best for efficiency.

– NathanOliver
9 hours ago




1




1





Nice! That's the kind of answer I was hoping for. It seems it doesn't fit as a generic solution to always reuse because of the lock overhead, but it's very nice to know.

– Kelno
8 hours ago





Nice! That's the kind of answer I was hoping for. It seems it doesn't fit as a generic solution to always reuse because of the lock overhead, but it's very nice to know.

– Kelno
8 hours ago













12














Some good ideas here, but I like to keep it a bit more simple:



void PrintToGameMasters()

std::string message;

for (Player* player : GetAllPlayers())

if (player->IsGameMaster())

if (message.empty())
message = GetComplicatedDebugMessage();

player->SendMessage(message);





Everybody can follow this, and it's cheap as chips… plus it's easy as pie to debug.






share|improve this answer




















  • 2





    Probably suitable for this case. But in general, what if message happens to be empty but still expensive to calculate?

    – sebrockm
    9 hours ago






  • 1





    @sebrockm Then you can introduce a bool hasMessage instead. Either way it's pretty trivial logic.

    – Lightness Races in Orbit
    9 hours ago












  • I do know it's trivial :) but then the entire question is trivial, yet OP asked it. So maybe it's not trivial for them :)

    – sebrockm
    9 hours ago






  • 2





    This is both short and simple. + vote for recognizing when not to use "cool" stuff

    – user1316208
    8 hours ago











  • This would perfectly do in this specific example, as well as the "hasMessage" for non-basic types cases, but I'm trying to find shorter pattern I can reuse, probably a wrapper around the message that would avoid the code clutter.

    – Kelno
    8 hours ago















12














Some good ideas here, but I like to keep it a bit more simple:



void PrintToGameMasters()

std::string message;

for (Player* player : GetAllPlayers())

if (player->IsGameMaster())

if (message.empty())
message = GetComplicatedDebugMessage();

player->SendMessage(message);





Everybody can follow this, and it's cheap as chips… plus it's easy as pie to debug.






share|improve this answer




















  • 2





    Probably suitable for this case. But in general, what if message happens to be empty but still expensive to calculate?

    – sebrockm
    9 hours ago






  • 1





    @sebrockm Then you can introduce a bool hasMessage instead. Either way it's pretty trivial logic.

    – Lightness Races in Orbit
    9 hours ago












  • I do know it's trivial :) but then the entire question is trivial, yet OP asked it. So maybe it's not trivial for them :)

    – sebrockm
    9 hours ago






  • 2





    This is both short and simple. + vote for recognizing when not to use "cool" stuff

    – user1316208
    8 hours ago











  • This would perfectly do in this specific example, as well as the "hasMessage" for non-basic types cases, but I'm trying to find shorter pattern I can reuse, probably a wrapper around the message that would avoid the code clutter.

    – Kelno
    8 hours ago













12












12








12







Some good ideas here, but I like to keep it a bit more simple:



void PrintToGameMasters()

std::string message;

for (Player* player : GetAllPlayers())

if (player->IsGameMaster())

if (message.empty())
message = GetComplicatedDebugMessage();

player->SendMessage(message);





Everybody can follow this, and it's cheap as chips… plus it's easy as pie to debug.






share|improve this answer













Some good ideas here, but I like to keep it a bit more simple:



void PrintToGameMasters()

std::string message;

for (Player* player : GetAllPlayers())

if (player->IsGameMaster())

if (message.empty())
message = GetComplicatedDebugMessage();

player->SendMessage(message);





Everybody can follow this, and it's cheap as chips… plus it's easy as pie to debug.







share|improve this answer












share|improve this answer



share|improve this answer










answered 9 hours ago









Lightness Races in OrbitLightness Races in Orbit

312k59 gold badges515 silver badges861 bronze badges




312k59 gold badges515 silver badges861 bronze badges










  • 2





    Probably suitable for this case. But in general, what if message happens to be empty but still expensive to calculate?

    – sebrockm
    9 hours ago






  • 1





    @sebrockm Then you can introduce a bool hasMessage instead. Either way it's pretty trivial logic.

    – Lightness Races in Orbit
    9 hours ago












  • I do know it's trivial :) but then the entire question is trivial, yet OP asked it. So maybe it's not trivial for them :)

    – sebrockm
    9 hours ago






  • 2





    This is both short and simple. + vote for recognizing when not to use "cool" stuff

    – user1316208
    8 hours ago











  • This would perfectly do in this specific example, as well as the "hasMessage" for non-basic types cases, but I'm trying to find shorter pattern I can reuse, probably a wrapper around the message that would avoid the code clutter.

    – Kelno
    8 hours ago












  • 2





    Probably suitable for this case. But in general, what if message happens to be empty but still expensive to calculate?

    – sebrockm
    9 hours ago






  • 1





    @sebrockm Then you can introduce a bool hasMessage instead. Either way it's pretty trivial logic.

    – Lightness Races in Orbit
    9 hours ago












  • I do know it's trivial :) but then the entire question is trivial, yet OP asked it. So maybe it's not trivial for them :)

    – sebrockm
    9 hours ago






  • 2





    This is both short and simple. + vote for recognizing when not to use "cool" stuff

    – user1316208
    8 hours ago











  • This would perfectly do in this specific example, as well as the "hasMessage" for non-basic types cases, but I'm trying to find shorter pattern I can reuse, probably a wrapper around the message that would avoid the code clutter.

    – Kelno
    8 hours ago







2




2





Probably suitable for this case. But in general, what if message happens to be empty but still expensive to calculate?

– sebrockm
9 hours ago





Probably suitable for this case. But in general, what if message happens to be empty but still expensive to calculate?

– sebrockm
9 hours ago




1




1





@sebrockm Then you can introduce a bool hasMessage instead. Either way it's pretty trivial logic.

– Lightness Races in Orbit
9 hours ago






@sebrockm Then you can introduce a bool hasMessage instead. Either way it's pretty trivial logic.

– Lightness Races in Orbit
9 hours ago














I do know it's trivial :) but then the entire question is trivial, yet OP asked it. So maybe it's not trivial for them :)

– sebrockm
9 hours ago





I do know it's trivial :) but then the entire question is trivial, yet OP asked it. So maybe it's not trivial for them :)

– sebrockm
9 hours ago




2




2





This is both short and simple. + vote for recognizing when not to use "cool" stuff

– user1316208
8 hours ago





This is both short and simple. + vote for recognizing when not to use "cool" stuff

– user1316208
8 hours ago













This would perfectly do in this specific example, as well as the "hasMessage" for non-basic types cases, but I'm trying to find shorter pattern I can reuse, probably a wrapper around the message that would avoid the code clutter.

– Kelno
8 hours ago





This would perfectly do in this specific example, as well as the "hasMessage" for non-basic types cases, but I'm trying to find shorter pattern I can reuse, probably a wrapper around the message that would avoid the code clutter.

– Kelno
8 hours ago











4














Wrap the message in a mutable lambda:



auto makeMessage = [message = std::string()]() mutable -> std::string&

if (message.empty())
message = GetComplicatedDebugMessage();

return message;
;

for (Player* player : GetAllPlayers())
if (player->IsGameMaster())
player->SendMessage(makeMessage());





share|improve this answer



























  • I like this one especially, I can make some more generic wrapper out of this easily.

    – Kelno
    8 hours ago












  • @Kelno And the boolean was useless anyway, since you can just check with empty().

    – Nikos C.
    7 hours ago















4














Wrap the message in a mutable lambda:



auto makeMessage = [message = std::string()]() mutable -> std::string&

if (message.empty())
message = GetComplicatedDebugMessage();

return message;
;

for (Player* player : GetAllPlayers())
if (player->IsGameMaster())
player->SendMessage(makeMessage());





share|improve this answer



























  • I like this one especially, I can make some more generic wrapper out of this easily.

    – Kelno
    8 hours ago












  • @Kelno And the boolean was useless anyway, since you can just check with empty().

    – Nikos C.
    7 hours ago













4












4








4







Wrap the message in a mutable lambda:



auto makeMessage = [message = std::string()]() mutable -> std::string&

if (message.empty())
message = GetComplicatedDebugMessage();

return message;
;

for (Player* player : GetAllPlayers())
if (player->IsGameMaster())
player->SendMessage(makeMessage());





share|improve this answer















Wrap the message in a mutable lambda:



auto makeMessage = [message = std::string()]() mutable -> std::string&

if (message.empty())
message = GetComplicatedDebugMessage();

return message;
;

for (Player* player : GetAllPlayers())
if (player->IsGameMaster())
player->SendMessage(makeMessage());






share|improve this answer














share|improve this answer



share|improve this answer








edited 7 hours ago

























answered 9 hours ago









Nikos C.Nikos C.

41.3k7 gold badges50 silver badges78 bronze badges




41.3k7 gold badges50 silver badges78 bronze badges















  • I like this one especially, I can make some more generic wrapper out of this easily.

    – Kelno
    8 hours ago












  • @Kelno And the boolean was useless anyway, since you can just check with empty().

    – Nikos C.
    7 hours ago

















  • I like this one especially, I can make some more generic wrapper out of this easily.

    – Kelno
    8 hours ago












  • @Kelno And the boolean was useless anyway, since you can just check with empty().

    – Nikos C.
    7 hours ago
















I like this one especially, I can make some more generic wrapper out of this easily.

– Kelno
8 hours ago






I like this one especially, I can make some more generic wrapper out of this easily.

– Kelno
8 hours ago














@Kelno And the boolean was useless anyway, since you can just check with empty().

– Nikos C.
7 hours ago





@Kelno And the boolean was useless anyway, since you can just check with empty().

– Nikos C.
7 hours ago











3














Use data-oriented design; keep two lists of players: game masters and non-game masters.



void PrintToGameMasters()

auto players = GetGameMasters(); // Returns ONLY game master players
if (players.begin() != players.end())
std::string message = GetComplicatedDebugMessage();
for (Player* player : players)
player->SendMessage(message);





The goal is to minimize if-statements inside loops.




P.S. Since you're developing a game, I want to add this link to Mike Acton's cppcon talk which you might find interesting.






share|improve this answer



























  • I like this a lot.

    – Lightness Races in Orbit
    52 mins ago















3














Use data-oriented design; keep two lists of players: game masters and non-game masters.



void PrintToGameMasters()

auto players = GetGameMasters(); // Returns ONLY game master players
if (players.begin() != players.end())
std::string message = GetComplicatedDebugMessage();
for (Player* player : players)
player->SendMessage(message);





The goal is to minimize if-statements inside loops.




P.S. Since you're developing a game, I want to add this link to Mike Acton's cppcon talk which you might find interesting.






share|improve this answer



























  • I like this a lot.

    – Lightness Races in Orbit
    52 mins ago













3












3








3







Use data-oriented design; keep two lists of players: game masters and non-game masters.



void PrintToGameMasters()

auto players = GetGameMasters(); // Returns ONLY game master players
if (players.begin() != players.end())
std::string message = GetComplicatedDebugMessage();
for (Player* player : players)
player->SendMessage(message);





The goal is to minimize if-statements inside loops.




P.S. Since you're developing a game, I want to add this link to Mike Acton's cppcon talk which you might find interesting.






share|improve this answer















Use data-oriented design; keep two lists of players: game masters and non-game masters.



void PrintToGameMasters()

auto players = GetGameMasters(); // Returns ONLY game master players
if (players.begin() != players.end())
std::string message = GetComplicatedDebugMessage();
for (Player* player : players)
player->SendMessage(message);





The goal is to minimize if-statements inside loops.




P.S. Since you're developing a game, I want to add this link to Mike Acton's cppcon talk which you might find interesting.







share|improve this answer














share|improve this answer



share|improve this answer








edited 8 hours ago

























answered 8 hours ago









rustyxrustyx

37k11 gold badges108 silver badges154 bronze badges




37k11 gold badges108 silver badges154 bronze badges















  • I like this a lot.

    – Lightness Races in Orbit
    52 mins ago

















  • I like this a lot.

    – Lightness Races in Orbit
    52 mins ago
















I like this a lot.

– Lightness Races in Orbit
52 mins ago





I like this a lot.

– Lightness Races in Orbit
52 mins ago











2














Whereas std::string has empty value which might mean "not computed", you might use more generally std::optional which handle empty string and non default constructible types:



void PrintToGameMasters()

std::optional<std::string> message;

for (Player* player : GetAllPlayers())

if (player->IsGameMaster())

if (!message)
message = GetComplicatedDebugMessage();

player->SendMessage(*message);








share|improve this answer

























  • This is good. It removes the reliance on "empty == not calculated yet" with absolutely no source code lines overhead. 👍

    – Lightness Races in Orbit
    50 mins ago











  • In fact, sod it, this is what I'd do.

    – Lightness Races in Orbit
    50 mins ago















2














Whereas std::string has empty value which might mean "not computed", you might use more generally std::optional which handle empty string and non default constructible types:



void PrintToGameMasters()

std::optional<std::string> message;

for (Player* player : GetAllPlayers())

if (player->IsGameMaster())

if (!message)
message = GetComplicatedDebugMessage();

player->SendMessage(*message);








share|improve this answer

























  • This is good. It removes the reliance on "empty == not calculated yet" with absolutely no source code lines overhead. 👍

    – Lightness Races in Orbit
    50 mins ago











  • In fact, sod it, this is what I'd do.

    – Lightness Races in Orbit
    50 mins ago













2












2








2







Whereas std::string has empty value which might mean "not computed", you might use more generally std::optional which handle empty string and non default constructible types:



void PrintToGameMasters()

std::optional<std::string> message;

for (Player* player : GetAllPlayers())

if (player->IsGameMaster())

if (!message)
message = GetComplicatedDebugMessage();

player->SendMessage(*message);








share|improve this answer













Whereas std::string has empty value which might mean "not computed", you might use more generally std::optional which handle empty string and non default constructible types:



void PrintToGameMasters()

std::optional<std::string> message;

for (Player* player : GetAllPlayers())

if (player->IsGameMaster())

if (!message)
message = GetComplicatedDebugMessage();

player->SendMessage(*message);









share|improve this answer












share|improve this answer



share|improve this answer










answered 1 hour ago









Jarod42Jarod42

128k12 gold badges113 silver badges201 bronze badges




128k12 gold badges113 silver badges201 bronze badges















  • This is good. It removes the reliance on "empty == not calculated yet" with absolutely no source code lines overhead. 👍

    – Lightness Races in Orbit
    50 mins ago











  • In fact, sod it, this is what I'd do.

    – Lightness Races in Orbit
    50 mins ago

















  • This is good. It removes the reliance on "empty == not calculated yet" with absolutely no source code lines overhead. 👍

    – Lightness Races in Orbit
    50 mins ago











  • In fact, sod it, this is what I'd do.

    – Lightness Races in Orbit
    50 mins ago
















This is good. It removes the reliance on "empty == not calculated yet" with absolutely no source code lines overhead. 👍

– Lightness Races in Orbit
50 mins ago





This is good. It removes the reliance on "empty == not calculated yet" with absolutely no source code lines overhead. 👍

– Lightness Races in Orbit
50 mins ago













In fact, sod it, this is what I'd do.

– Lightness Races in Orbit
50 mins ago





In fact, sod it, this is what I'd do.

– Lightness Races in Orbit
50 mins ago











1














Not sure if this is the best pattern, but you can delay computation with a lambda:



void PrintToGameMasters()

std::string message = "";
auto getDebugMessage = [&message]() -> const std::string&
if (message.empty())
message = GetComplicatedDebugMessage();

return message;
;

for (Player* player : GetAllPlayers())
if (player->IsGameMaster())
player->SendMessage(getDebugMessage());






share|improve this answer



























  • getDebug/getMessage

    – Lightness Races in Orbit
    9 hours ago






  • 1





    This also doesn't assign to message on the first call so message is always empty.

    – NathanOliver
    9 hours ago











  • Indeed. Needs to assign in the conditionals, then return message unconditionally. Add a reference return type too (I think?)

    – Lightness Races in Orbit
    9 hours ago











  • @LightnessRacesinOrbit Defenitly needs to return by reference or it defeats the point.

    – NathanOliver
    9 hours ago











  • What I mean is there may be some other "clever" antics that can achieve the same goal while keeping the RT deduction (return (message) or some nonsense like that?) but I deliberately don't bother keeping track of all the various decltype monostrosities because I value my sanity (slightly)!

    – Lightness Races in Orbit
    9 hours ago
















1














Not sure if this is the best pattern, but you can delay computation with a lambda:



void PrintToGameMasters()

std::string message = "";
auto getDebugMessage = [&message]() -> const std::string&
if (message.empty())
message = GetComplicatedDebugMessage();

return message;
;

for (Player* player : GetAllPlayers())
if (player->IsGameMaster())
player->SendMessage(getDebugMessage());






share|improve this answer



























  • getDebug/getMessage

    – Lightness Races in Orbit
    9 hours ago






  • 1





    This also doesn't assign to message on the first call so message is always empty.

    – NathanOliver
    9 hours ago











  • Indeed. Needs to assign in the conditionals, then return message unconditionally. Add a reference return type too (I think?)

    – Lightness Races in Orbit
    9 hours ago











  • @LightnessRacesinOrbit Defenitly needs to return by reference or it defeats the point.

    – NathanOliver
    9 hours ago











  • What I mean is there may be some other "clever" antics that can achieve the same goal while keeping the RT deduction (return (message) or some nonsense like that?) but I deliberately don't bother keeping track of all the various decltype monostrosities because I value my sanity (slightly)!

    – Lightness Races in Orbit
    9 hours ago














1












1








1







Not sure if this is the best pattern, but you can delay computation with a lambda:



void PrintToGameMasters()

std::string message = "";
auto getDebugMessage = [&message]() -> const std::string&
if (message.empty())
message = GetComplicatedDebugMessage();

return message;
;

for (Player* player : GetAllPlayers())
if (player->IsGameMaster())
player->SendMessage(getDebugMessage());






share|improve this answer















Not sure if this is the best pattern, but you can delay computation with a lambda:



void PrintToGameMasters()

std::string message = "";
auto getDebugMessage = [&message]() -> const std::string&
if (message.empty())
message = GetComplicatedDebugMessage();

return message;
;

for (Player* player : GetAllPlayers())
if (player->IsGameMaster())
player->SendMessage(getDebugMessage());







share|improve this answer














share|improve this answer



share|improve this answer








edited 9 hours ago

























answered 9 hours ago









0x54530x5453

4,49113 silver badges25 bronze badges




4,49113 silver badges25 bronze badges















  • getDebug/getMessage

    – Lightness Races in Orbit
    9 hours ago






  • 1





    This also doesn't assign to message on the first call so message is always empty.

    – NathanOliver
    9 hours ago











  • Indeed. Needs to assign in the conditionals, then return message unconditionally. Add a reference return type too (I think?)

    – Lightness Races in Orbit
    9 hours ago











  • @LightnessRacesinOrbit Defenitly needs to return by reference or it defeats the point.

    – NathanOliver
    9 hours ago











  • What I mean is there may be some other "clever" antics that can achieve the same goal while keeping the RT deduction (return (message) or some nonsense like that?) but I deliberately don't bother keeping track of all the various decltype monostrosities because I value my sanity (slightly)!

    – Lightness Races in Orbit
    9 hours ago


















  • getDebug/getMessage

    – Lightness Races in Orbit
    9 hours ago






  • 1





    This also doesn't assign to message on the first call so message is always empty.

    – NathanOliver
    9 hours ago











  • Indeed. Needs to assign in the conditionals, then return message unconditionally. Add a reference return type too (I think?)

    – Lightness Races in Orbit
    9 hours ago











  • @LightnessRacesinOrbit Defenitly needs to return by reference or it defeats the point.

    – NathanOliver
    9 hours ago











  • What I mean is there may be some other "clever" antics that can achieve the same goal while keeping the RT deduction (return (message) or some nonsense like that?) but I deliberately don't bother keeping track of all the various decltype monostrosities because I value my sanity (slightly)!

    – Lightness Races in Orbit
    9 hours ago

















getDebug/getMessage

– Lightness Races in Orbit
9 hours ago





getDebug/getMessage

– Lightness Races in Orbit
9 hours ago




1




1





This also doesn't assign to message on the first call so message is always empty.

– NathanOliver
9 hours ago





This also doesn't assign to message on the first call so message is always empty.

– NathanOliver
9 hours ago













Indeed. Needs to assign in the conditionals, then return message unconditionally. Add a reference return type too (I think?)

– Lightness Races in Orbit
9 hours ago





Indeed. Needs to assign in the conditionals, then return message unconditionally. Add a reference return type too (I think?)

– Lightness Races in Orbit
9 hours ago













@LightnessRacesinOrbit Defenitly needs to return by reference or it defeats the point.

– NathanOliver
9 hours ago





@LightnessRacesinOrbit Defenitly needs to return by reference or it defeats the point.

– NathanOliver
9 hours ago













What I mean is there may be some other "clever" antics that can achieve the same goal while keeping the RT deduction (return (message) or some nonsense like that?) but I deliberately don't bother keeping track of all the various decltype monostrosities because I value my sanity (slightly)!

– Lightness Races in Orbit
9 hours ago






What I mean is there may be some other "clever" antics that can achieve the same goal while keeping the RT deduction (return (message) or some nonsense like that?) but I deliberately don't bother keeping track of all the various decltype monostrosities because I value my sanity (slightly)!

– Lightness Races in Orbit
9 hours ago












0














Another simplistic approach using static keyword:



void PrintToGameMasters()

for (Player* player : GetAllPlayers())
if (player->IsGameMaster())

static std::string message = GetComplicatedDebugMessage();
player->SendMessage(message);







share|improve this answer



























  • @RemyLebeau: Thanks again, how is the code now?

    – seccpur
    7 hours ago






  • 1





    Do note that this means the string will always be the same. If GetComplicatedDebugMessage() can change it's return value in between calls to PrintToGameMasters() then you won't pick up on that.

    – NathanOliver
    6 hours ago
















0














Another simplistic approach using static keyword:



void PrintToGameMasters()

for (Player* player : GetAllPlayers())
if (player->IsGameMaster())

static std::string message = GetComplicatedDebugMessage();
player->SendMessage(message);







share|improve this answer



























  • @RemyLebeau: Thanks again, how is the code now?

    – seccpur
    7 hours ago






  • 1





    Do note that this means the string will always be the same. If GetComplicatedDebugMessage() can change it's return value in between calls to PrintToGameMasters() then you won't pick up on that.

    – NathanOliver
    6 hours ago














0












0








0







Another simplistic approach using static keyword:



void PrintToGameMasters()

for (Player* player : GetAllPlayers())
if (player->IsGameMaster())

static std::string message = GetComplicatedDebugMessage();
player->SendMessage(message);







share|improve this answer















Another simplistic approach using static keyword:



void PrintToGameMasters()

for (Player* player : GetAllPlayers())
if (player->IsGameMaster())

static std::string message = GetComplicatedDebugMessage();
player->SendMessage(message);








share|improve this answer














share|improve this answer



share|improve this answer








edited 7 hours ago

























answered 7 hours ago









seccpurseccpur

3,5282 gold badges6 silver badges16 bronze badges




3,5282 gold badges6 silver badges16 bronze badges















  • @RemyLebeau: Thanks again, how is the code now?

    – seccpur
    7 hours ago






  • 1





    Do note that this means the string will always be the same. If GetComplicatedDebugMessage() can change it's return value in between calls to PrintToGameMasters() then you won't pick up on that.

    – NathanOliver
    6 hours ago


















  • @RemyLebeau: Thanks again, how is the code now?

    – seccpur
    7 hours ago






  • 1





    Do note that this means the string will always be the same. If GetComplicatedDebugMessage() can change it's return value in between calls to PrintToGameMasters() then you won't pick up on that.

    – NathanOliver
    6 hours ago

















@RemyLebeau: Thanks again, how is the code now?

– seccpur
7 hours ago





@RemyLebeau: Thanks again, how is the code now?

– seccpur
7 hours ago




1




1





Do note that this means the string will always be the same. If GetComplicatedDebugMessage() can change it's return value in between calls to PrintToGameMasters() then you won't pick up on that.

– NathanOliver
6 hours ago






Do note that this means the string will always be the same. If GetComplicatedDebugMessage() can change it's return value in between calls to PrintToGameMasters() then you won't pick up on that.

– NathanOliver
6 hours ago












0














Really hope this helps



Try maybe implement this logic:



#include <iostream>

using namespace std;

int main()

bool GameMaster,first_time,used_before;

GameMaster = true;
first_time = false;
used_before = false;

GameMaster = first_time;
first_time = used_before;


for( int i = 0; i < 5; i++ )

if(GameMaster==used_before)
cout<<" First Time";
GameMaster = true;


if(GameMaster!=used_before)
cout<<" Old News";



return 0;



With Response:



 First Time Old News Old News Old News Old News Old News 





share|improve this answer



























  • FWIW i = i + 1 can be replaced by ++i, if(GameMaster!=used_before) can be replaced by else, You can also get rid of two of the three bool's as you only need one flag to know if one thing has been done.

    – NathanOliver
    8 hours ago







  • 1





    This is absolutely bizarre code!! Why do you have THREE bool variable when only ONE is actually really used? "used_before" is assigned false at initialisation then never changed! "first_time" is assigned false and then re-assigned "used_before" which is also ALWAYS false! And then, neither "first_time" nor "used_before" are ever given other values in the loop!

    – Adrian
    8 hours ago











  • I didn't say im expert, I was trying to pass variable values, without affecting the previous one. I used this logic before for button polling and it did the job, I didn't consider that bc he only needs to read the change once, 3 variables are overkill. Looks like it could have been done easier, thank you for your suggestions.

    – Andrei Elekes
    2 hours ago











  • Dunno, seems too wordy. Also fix your indentation!!

    – Lightness Races in Orbit
    51 mins ago
















0














Really hope this helps



Try maybe implement this logic:



#include <iostream>

using namespace std;

int main()

bool GameMaster,first_time,used_before;

GameMaster = true;
first_time = false;
used_before = false;

GameMaster = first_time;
first_time = used_before;


for( int i = 0; i < 5; i++ )

if(GameMaster==used_before)
cout<<" First Time";
GameMaster = true;


if(GameMaster!=used_before)
cout<<" Old News";



return 0;



With Response:



 First Time Old News Old News Old News Old News Old News 





share|improve this answer



























  • FWIW i = i + 1 can be replaced by ++i, if(GameMaster!=used_before) can be replaced by else, You can also get rid of two of the three bool's as you only need one flag to know if one thing has been done.

    – NathanOliver
    8 hours ago







  • 1





    This is absolutely bizarre code!! Why do you have THREE bool variable when only ONE is actually really used? "used_before" is assigned false at initialisation then never changed! "first_time" is assigned false and then re-assigned "used_before" which is also ALWAYS false! And then, neither "first_time" nor "used_before" are ever given other values in the loop!

    – Adrian
    8 hours ago











  • I didn't say im expert, I was trying to pass variable values, without affecting the previous one. I used this logic before for button polling and it did the job, I didn't consider that bc he only needs to read the change once, 3 variables are overkill. Looks like it could have been done easier, thank you for your suggestions.

    – Andrei Elekes
    2 hours ago











  • Dunno, seems too wordy. Also fix your indentation!!

    – Lightness Races in Orbit
    51 mins ago














0












0








0







Really hope this helps



Try maybe implement this logic:



#include <iostream>

using namespace std;

int main()

bool GameMaster,first_time,used_before;

GameMaster = true;
first_time = false;
used_before = false;

GameMaster = first_time;
first_time = used_before;


for( int i = 0; i < 5; i++ )

if(GameMaster==used_before)
cout<<" First Time";
GameMaster = true;


if(GameMaster!=used_before)
cout<<" Old News";



return 0;



With Response:



 First Time Old News Old News Old News Old News Old News 





share|improve this answer















Really hope this helps



Try maybe implement this logic:



#include <iostream>

using namespace std;

int main()

bool GameMaster,first_time,used_before;

GameMaster = true;
first_time = false;
used_before = false;

GameMaster = first_time;
first_time = used_before;


for( int i = 0; i < 5; i++ )

if(GameMaster==used_before)
cout<<" First Time";
GameMaster = true;


if(GameMaster!=used_before)
cout<<" Old News";



return 0;



With Response:



 First Time Old News Old News Old News Old News Old News 






share|improve this answer














share|improve this answer



share|improve this answer








edited 2 hours ago

























answered 9 hours ago









Andrei ElekesAndrei Elekes

94 bronze badges




94 bronze badges















  • FWIW i = i + 1 can be replaced by ++i, if(GameMaster!=used_before) can be replaced by else, You can also get rid of two of the three bool's as you only need one flag to know if one thing has been done.

    – NathanOliver
    8 hours ago







  • 1





    This is absolutely bizarre code!! Why do you have THREE bool variable when only ONE is actually really used? "used_before" is assigned false at initialisation then never changed! "first_time" is assigned false and then re-assigned "used_before" which is also ALWAYS false! And then, neither "first_time" nor "used_before" are ever given other values in the loop!

    – Adrian
    8 hours ago











  • I didn't say im expert, I was trying to pass variable values, without affecting the previous one. I used this logic before for button polling and it did the job, I didn't consider that bc he only needs to read the change once, 3 variables are overkill. Looks like it could have been done easier, thank you for your suggestions.

    – Andrei Elekes
    2 hours ago











  • Dunno, seems too wordy. Also fix your indentation!!

    – Lightness Races in Orbit
    51 mins ago


















  • FWIW i = i + 1 can be replaced by ++i, if(GameMaster!=used_before) can be replaced by else, You can also get rid of two of the three bool's as you only need one flag to know if one thing has been done.

    – NathanOliver
    8 hours ago







  • 1





    This is absolutely bizarre code!! Why do you have THREE bool variable when only ONE is actually really used? "used_before" is assigned false at initialisation then never changed! "first_time" is assigned false and then re-assigned "used_before" which is also ALWAYS false! And then, neither "first_time" nor "used_before" are ever given other values in the loop!

    – Adrian
    8 hours ago











  • I didn't say im expert, I was trying to pass variable values, without affecting the previous one. I used this logic before for button polling and it did the job, I didn't consider that bc he only needs to read the change once, 3 variables are overkill. Looks like it could have been done easier, thank you for your suggestions.

    – Andrei Elekes
    2 hours ago











  • Dunno, seems too wordy. Also fix your indentation!!

    – Lightness Races in Orbit
    51 mins ago

















FWIW i = i + 1 can be replaced by ++i, if(GameMaster!=used_before) can be replaced by else, You can also get rid of two of the three bool's as you only need one flag to know if one thing has been done.

– NathanOliver
8 hours ago






FWIW i = i + 1 can be replaced by ++i, if(GameMaster!=used_before) can be replaced by else, You can also get rid of two of the three bool's as you only need one flag to know if one thing has been done.

– NathanOliver
8 hours ago





1




1





This is absolutely bizarre code!! Why do you have THREE bool variable when only ONE is actually really used? "used_before" is assigned false at initialisation then never changed! "first_time" is assigned false and then re-assigned "used_before" which is also ALWAYS false! And then, neither "first_time" nor "used_before" are ever given other values in the loop!

– Adrian
8 hours ago





This is absolutely bizarre code!! Why do you have THREE bool variable when only ONE is actually really used? "used_before" is assigned false at initialisation then never changed! "first_time" is assigned false and then re-assigned "used_before" which is also ALWAYS false! And then, neither "first_time" nor "used_before" are ever given other values in the loop!

– Adrian
8 hours ago













I didn't say im expert, I was trying to pass variable values, without affecting the previous one. I used this logic before for button polling and it did the job, I didn't consider that bc he only needs to read the change once, 3 variables are overkill. Looks like it could have been done easier, thank you for your suggestions.

– Andrei Elekes
2 hours ago





I didn't say im expert, I was trying to pass variable values, without affecting the previous one. I used this logic before for button polling and it did the job, I didn't consider that bc he only needs to read the change once, 3 variables are overkill. Looks like it could have been done easier, thank you for your suggestions.

– Andrei Elekes
2 hours ago













Dunno, seems too wordy. Also fix your indentation!!

– Lightness Races in Orbit
51 mins ago






Dunno, seems too wordy. Also fix your indentation!!

– Lightness Races in Orbit
51 mins ago


















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57510792%2fwhats-a-good-pattern-to-calculate-a-variable-only-when-it-is-used-the-first-tim%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

Ласкавець круглолистий Зміст Опис | Поширення | Галерея | Примітки | Посилання | Навігаційне меню58171138361-22960890446Bupleurum rotundifoliumEuro+Med PlantbasePlants of the World Online — Kew ScienceGermplasm Resources Information Network (GRIN)Ласкавецькн. VI : Літери Ком — Левиправивши або дописавши її