Telegram Group & Telegram Channel
🧠 Как static в C++ помогает бороться с неожиданностями

Сейчас покажу вам интересную особенность ключевого слова static в контексте функций — то, что часто забывают даже опытные разработчики.

Представим простую ситуацию:


void logCall() {
int counter = 0;
counter++;
std::cout << "Called " << counter << " times\n";
}


Кажется, всё хорошо… Но функция всегда выводит Called 1 times, потому что переменная counter создаётся заново при каждом вызове.

Теперь добавим static:


void logCall() {
static int counter = 0;
counter++;
std::cout << "Called " << counter << " times\n";
}


А вот теперь магия — переменная counter сохраняет своё значение между вызовами! Это отличный способ реализовать простой счётчик, кэш или ленивую инициализацию прямо в функции.

📌 Важно: static делает переменную локальной по области видимости, но глобальной по времени жизни.

А вы где применяли static неожиданным образом? Делитесь в комментариях! 👇

➡️ @cpp_geek



tg-me.com/cpp_geek/308
Create:
Last Update:

🧠 Как static в C++ помогает бороться с неожиданностями

Сейчас покажу вам интересную особенность ключевого слова static в контексте функций — то, что часто забывают даже опытные разработчики.

Представим простую ситуацию:


void logCall() {
int counter = 0;
counter++;
std::cout << "Called " << counter << " times\n";
}


Кажется, всё хорошо… Но функция всегда выводит Called 1 times, потому что переменная counter создаётся заново при каждом вызове.

Теперь добавим static:


void logCall() {
static int counter = 0;
counter++;
std::cout << "Called " << counter << " times\n";
}


А вот теперь магия — переменная counter сохраняет своё значение между вызовами! Это отличный способ реализовать простой счётчик, кэш или ленивую инициализацию прямо в функции.

📌 Важно: static делает переменную локальной по области видимости, но глобальной по времени жизни.

А вы где применяли static неожиданным образом? Делитесь в комментариях! 👇

➡️ @cpp_geek

BY C++ geek


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/cpp_geek/308

View MORE
Open in Telegram


C geek Telegram | DID YOU KNOW?

Date: |

How to Invest in Bitcoin?

Like a stock, you can buy and hold Bitcoin as an investment. You can even now do so in special retirement accounts called Bitcoin IRAs. No matter where you choose to hold your Bitcoin, people’s philosophies on how to invest it vary: Some buy and hold long term, some buy and aim to sell after a price rally, and others bet on its price decreasing. Bitcoin’s price over time has experienced big price swings, going as low as $5,165 and as high as $28,990 in 2020 alone. “I think in some places, people might be using Bitcoin to pay for things, but the truth is that it’s an asset that looks like it’s going to be increasing in value relatively quickly for some time,” Marquez says. “So why would you sell something that’s going to be worth so much more next year than it is today? The majority of people that hold it are long-term investors.”

Should I buy bitcoin?

“To the extent it is used I fear it’s often for illicit finance. It’s an extremely inefficient way of conducting transactions, and the amount of energy that’s consumed in processing those transactions is staggering,” the former Fed chairwoman said. Yellen’s comments have been cited as a reason for bitcoin’s recent losses. However, Yellen’s assessment of bitcoin as a inefficient medium of exchange is an important point and one that has already been raised in the past by bitcoin bulls. Using a volatile asset in exchange for goods and services makes little sense if the asset can tumble 10% in a day, or surge 80% over the course of a two months as bitcoin has done in 2021, critics argue. To put a finer point on it, over the past 12 months bitcoin has registered 8 corrections, defined as a decline from a recent peak of at least 10% but not more than 20%, and two bear markets, which are defined as falls of 20% or more, according to Dow Jones Market Data.

C geek from ms


Telegram C++ geek
FROM USA