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: |

NEWS: Telegram supports Facetime video calls NOW!

Secure video calling is in high demand. As an alternative to Zoom, many people are using end-to-end encrypted apps such as WhatsApp, FaceTime or Signal to speak to friends and family face-to-face since coronavirus lockdowns started to take place across the world. There’s another option—secure communications app Telegram just added video calling to its feature set, available on both iOS and Android. The new feature is also super secure—like Signal and WhatsApp and unlike Zoom (yet), video calls will be end-to-end encrypted.

That strategy is the acquisition of a value-priced company by a growth company. Using the growth company's higher-priced stock for the acquisition can produce outsized revenue and earnings growth. Even better is the use of cash, particularly in a growth period when financial aggressiveness is accepted and even positively viewed.he key public rationale behind this strategy is synergy - the 1+1=3 view. In many cases, synergy does occur and is valuable. However, in other cases, particularly as the strategy gains popularity, it doesn't. Joining two different organizations, workforces and cultures is a challenge. Simply putting two separate organizations together necessarily creates disruptions and conflicts that can undermine both operations.

C geek from ye


Telegram C++ geek
FROM USA