惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
小众软件
小众软件
爱范儿
爱范儿
Y
Y Combinator Blog
博客园 - Franky
美团技术团队
博客园 - 【当耐特】
The Cloudflare Blog
罗磊的独立博客
Hugging Face - Blog
Hugging Face - Blog
Jina AI
Jina AI
IT之家
IT之家
人人都是产品经理
人人都是产品经理
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
大猫的无限游戏
大猫的无限游戏
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 聂微东
WordPress大学
WordPress大学
V
Visual Studio Blog
博客园_首页
阮一峰的网络日志
阮一峰的网络日志
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
有赞技术团队
有赞技术团队

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Static in the house - C++ tales #1
Richard Toth · 2026-06-17 · via DEV Community
Cover image for Static in the house - C++ tales #1

Richard Toth

What is static

In C++, static is a keyword that primarily affects a variable's storage duration. A variable declared as static exists for the entire lifetime of the program.

However, there is a little more to it. Depending on where it is used, static can also affect a symbol's visibility, which is known as linkage.

Static: The Local Hero

When a variable is declared inside a function, it can only be accessed within that function. This is true for both automatic and static local variables. The difference lies in their lifetime. Automatic variables are created every time the function is called and destroyed when the function returns. A local static variable, on the other hand, is initialized only once and remains alive until the program terminates.

Although the variable continues to exist after the function returns, it is still only accessible from within the function where it was declared. Because its lifetime extends beyond the function call, a local static variable is not typically stored on the stack. It also preserves its value between function calls.

Example time

Here is a little showcase code:

#include <cstdio>

void test_static() {
  static int count{};
  int other_count{};

  count++;
  other_count++;

  printf("The test_static func is called %d times!!!\n", count);
  printf("This is other_count >> %d\n", other_count);
}

int main() {
  test_static();
  test_static();
  test_static();

  return 0;
}

...and the output:

The test_static func is called 1 times!!!
This is other_count >> 1
-------------------------------------------------------
The test_static func is called 2 times!!!
This is other_count >> 1
-------------------------------------------------------
The test_static func is called 3 times!!!
This is other_count >> 1
-------------------------------------------------------

Here, we have a test_static function with a static and automatic variable: count and other_count. In the output, it can be easily what happens with this two little guy. The count - what is a static variable of the test_static funtion - keeps the value and in every function call it is incremented and keeps and increase the value while the other_count is incremented, too although it cannot keep the own value between the function calls.

Static, the member

The behavior of the static is pretty similar in classes but have some differencies, too.

Let's check this:

class PlanetOfTheSolarSystem {
  public:
    static std::string our_star;
    std::string planet_name;

    PlanetOfTheSolarSystem(std::string n) {
      this->planet_name = n;
    }

    std::string get_planet_name() {
      return this->planet_name;
    }
};

std::string PlanetOfTheSolarSystem::our_star{ "Sun (other name is Sol)" };

The PlanetOfTheSolarSystem class has two variable our_star and the planet_name. While the planet_name is declared in the constructor, the static varialbe - our_star - is declared outside of the class, and a different syntax is used to it. The reason is the static member belongs to class and not to the object.

void print_planets_star(std::string planet_name, std::string star_of_the_planet) {
  printf("Star of the %s is %s\n", planet_name.c_str(), star_of_the_planet.c_str());
}

int main() {
  PlanetOfTheSolarSystem venus{ "Venus" };
  PlanetOfTheSolarSystem earth{ "Earth" };

  print_planets_star(venus.get_planet_name(), venus.our_star);
  print_planets_star(earth.get_planet_name(), earth.our_star);

  return 0;
}

Star of the Venus is Sun (other name is Sol)
Star of the Earth is Sun (other name is Sol)

This example code and the output show us the essence of the static member. The venus and the earth objects point to same variable.

Conclusion

In a nutshell, static is an essential C++ feature for creating data that must persist throughout the program's execution. When used inside functions, it allows values to survive between function calls. When used as a class member, it creates data shared by all instances of the class. In other contexts, it can also affect symbol visibility and linkage.

Understanding static is important because it appears frequently in real-world C++ code and forms the basis of several common programming techniques and design patterns.

Thanks for reading, and keep learning!