Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

double dash before a variable in C++

Tags:

c++

operators

Sorry if this is a beginner question, but I could not find an answer anywhere - I came across a class destructor in C++, in which there is

--num_strings;

I am wondering what the double dash means. Any help is appreciated, thanks. Below are parts of the header and cpp files:

// strngbad.h
#include <iostream>
class StringBad
{
private: 
    char * str;
    int len;
    static int num_strings;

public:
    StringBad(const char * s);
    StringBad();
    ~StringBad();
};

//  strngbad.cpp
#include <cstring>
#include "strngbad.h"
using std::cout;
....
....
....

StringBad::StringBad(const char *s)
{
    len = std::strlen(s);
    str = new char[len + 1];
    std::strcpy(str, s);
    num_strings++;
}

StringBad::~StringBad()
{
    --num_strings;
    delete [] str;
}
like image 354
Jerry Hu Avatar asked Mar 25 '26 16:03

Jerry Hu


1 Answers

Its the prefix decrement operator. It subtracts 1 from the variable and stores the result back in the variable. As an expression, it has the value of the result after the decrement. There's also a postfix decrement operator that behaves identically except the value of the expression is the variable value before the decrement.

(That's because num_strings is an int. Of course, like most operators in C++, if the variable is a class, it can define its own semantics for the prefix -- operator, so all bets are off as to what it does.)

like image 190
Ted Hopp Avatar answered Mar 28 '26 08:03

Ted Hopp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!