genfy
genfy

Reputation: 155

Incrementing a struct value in a for loop returns the same value each time

I'm just trying to run this simple line of code:

for (Client c : clients) {
    c.timeSinceLastPacket++;
    std::cout << c.timeSinceLastPacket << std::endl;
}

Unfortunately this always returns 1 after the increment. If I put a print before the increment it returns 0.

Here is my struct:

struct Client {
    int timeSinceLastPacket = 0;
    sf::IpAddress ip;
    unsigned short port = 0;
    unsigned short id = 0;
};

I'm using SFML.

Here's what I've tried:

The code isn't too long but I don't want to put it in the question. I'll link you to it here:

Server.h

Server.cpp

Upvotes: 0

Views: 140

Answers (2)

3Dave
3Dave

Reputation: 29041

By typing the loop variable as Client, you're making a copy of the element in the array on every iteration. Changes within the loop update the copy, not the original item stored in clients.

Make it a reference instead:

for (Client& c : clients) {

Unlike Java or C#, C++ defaults to value types rather than references, so you must explicitly state that you want a reference (or a pointer, but the syntax is slightly messier).

Using a non-reference type here can also lead to some perf issues if the type is complex, or performs significant processing its copy constructor. (That's not really a concern for the type you've outlined here, but can be an issue in other cases.)

Upvotes: 4

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385108

for (Client c : clients) {

Here you make a copy, named c. Your original in clients is unaffected.

If you want to mutate the original elements, use a reference:

for (Client& c : clients) {

Upvotes: 10

Related Questions