Eat. Sleep. Code: The Computer Programming Thread, Ver. 010

I heard you guys are talking about pointers.

http://snag.gy/TCm6d.jpg

The way I’ve seen it presented is as this thing that you have to have. Describing it like an AA makes more sense if they aren’t actually necessary and instead make things only make things more efficient.


my professor emailed that to all of us :rofl:.

I understand reference variables perfectly fine but if I ever do run into trouble understanding pointers I’ll run back here crying.

maybe not the best analogy


imo you should have it. if you get through a CS program w/o understanding pointers your school has definitely failed you. but its conceivable that there are professional programmers that don’t understand pointers, especially considering how forgiving with memory many modern languages are, and robust libraries with objects built with pointers, but with hidden implementation so you don’t really need to understand them.

I would probably not hire someone who didn’t understand pointers.

I’ve just been studying programming on my own. I started with C, felt it was useless, moved onto C++, backed off when I ran into pointers because I didn’t get them, went to C# which is what I putzing around with now.

I’ll go back to C++ eventually since that is the language that I want to work in (and I kind of hate C#), but I rather work on logic/flow now than work with a more powerful and nuanced language.

Depends what language we’re talking about. In C or C++ they’re necessary for anything real because you can’t dynamically allocate memory without them.
Any other language, and you still basically need them to allocate memory but it’s probably wrapped up in some nicer syntax and garbage collection.

Edit: Actually this may not apply to functional programming languages. Not my forté those.

C# is great!*

*with Visual Studio and MSDN Documentation assist

Once I learned the fundamentals of memory, pointers were a godsend. References are nice when it comes to user created data types and languages that automatically reference for you. But uh
 those languages remove pointers for a reason.

Pointers are great. If the language has them, odds are you should be using them somewhere in your code. If not, it’s not because there are workarounds to avoid them, but because you’re essentially programming in a functional sort of manner. Might as well whip out the Lisp/Scheme if you’re never allocating memory.

Right now I’m having more problems with all the const stuff C++ has.

The part about pointers I’m more worried about is the part where you have to make sure you clean up when you’re done.

Sent from my SPH-D700 using Tapatalk 2

Consts? Such as how arrays need to be defined with const values?

C++ isn’t too hard to cleanup. Even if you do forget to clean up the OS will take care of it sooner or later.

Yeah the not changing stuff and changing stuff, stuff?

Like doing a method where the parameter passed can change, and then doing the same method where it can.

Const on the outside of a method for example.

Sent from my SPH-D700 using Tapatalk 2

For a function parameter “const int x”, the meaning is obvious. (also equivalent to “int const x”)
This is like some constant value in a math equation and you need it to not change.

The tricky part of the syntax comes from understanding what each constant means with pointers, but fortunately there are just four cases:



Pointers and const Type Qualifier:
The const type qualifier can make things a little confusing when it is used with pointer declarations.
There are only four cases, so just look it up when you need to remember.
The four cases:
  const int * const ip;  /* The pointer *ip is const
                            and the data it points at is also const */
        int * const ip;  /* The pointer *ip is const              */
  const int *       ip;  /* The data *ip is pointing at is const      */
        int *       ip;  /* Nothing is const                      */


edit:
Just changing the font fucks up a post. I’ve hated the editor on this forum for a long time.

@Pimp Wily
Sorry I have one more question about the code you helped me with.



int targetNum = 1000000;
for(int i = 1; i < targetNum/2; i++)
{
  int sum = i;
  for(int j = i + 1; j < targetNum/2; j++)
  {
    sum += j;
    if(sum == targetNum)
    //output here all ints from i to j, add up to 1,000,000
    else if (sum > targetNum)
      break;
  }
}


How exactly would you output those numbers in between these two? I originally just figured a simple printf until i == j would work but I am getting the same number when i should see the last sequence should in fact be
199998 199999 200000 200001 200002

I was referring to method declaration too. As in creating a method and having to define in its signature whether its allowed to change what called it.

When you put const to the right of the method.

Sent from my SPH-D700 using Tapatalk 2

This is what you’re talking about then:



constArray.Get(5)=42; // Error! (Calls: int const & MyArray::Get(int) const)


The get function is constant, saying don’t fuck with my data or else I’ll crash/compile error.

like this



for(int curNum = i; curNum <= j; curNum++)
   printf(curNum + " ");


My guess is you’re reusing the I variable so it’s never incrementing. which if it did, would throw off the algorithm and skip numbers anyway

I never knew this. Good stuff.

Then it means that the method promises not to change any members of the class [basically].*



class A
{
  public:
    int a;
    int BadMethod() const
    {
        a = 1;  // Compiler error: const methods aren't allowed to modify member variables
        return a;
    }
    int GoodMethod()
    {
        a = 1;  // Ok: Method is not const
        return a;
    }
    int ConstMethod() const
    {
        int b = 1; // Ok; const methods are allowed to modify local variables
        return b;
    }
};
 
A anInstance;
anInstance.ConstMethod(); // ok to call const method on non-const object
anInstance.GoodMethod();  // ok to call non-const method on non-const object
 
const A &constRef = anInstance; // create a const reference; this can't be used to change the object it refers to
constRef.ConstMethod(); // ok to call const method on const object
constRef.GoodMethod();  // Compiler error: cannot call a non-const method on a const object


If a method can be made const it’s generally considered good practice to declare it const. If you don’t intend to change an object you pass it as a const reference. That way if you accidentally try to change something you didn’t mean to (or weren’t supposed to), you end up calling a non-const method on a const object and the compiler flags it as an error.

*In C++11 a const method should also be thread safe or else you’ll run into problems. That one’s not guaranteed by the language though. (But parts of the standard library assume it.)

Actually, let me give a more practical example of using const references too. (Though it may be diverging some.)



class Month
{
    private:
        std::string mName;
        int mNumber;
        bool mHasMyBirthday;
    public:
        Month(int number)
        {
            mHasMyBirthday = false;
            mNumber = number;
            if (number == 1) { mName = "January"; }
            else if (number == 2) { mName = "February"; }
            // and so on
        }
        const std::string &GetName() const
        {
            return mName;
        }
        bool &HasMyBirthday()
        {
            return mHasMyBirthday;
        }
};
 
Month Jan(1);


Month::GetName() is const because it doesn’t need to modify the class. If we give someone an instance of Month that they’re not allowed to change (that is, it’s const) they’ll still be able to see what the name is (because they can call the const method).
Since it returns a const reference the compiler will not allow someone to write
[INDENT=1]Jan.GetName() == “February”;[/INDENT]
which is good–if we let them do that then mName and mNumber wouldn’t match. (So in a real class we would probably provide some method that set both at once–and it wouldn’t be const.)

It is legal to write
[INDENT=1]Jan.HasMyBirthday() = true;[/INDENT]
and that will change Jan.mHasMyBirthday–we’re calling a non-const method of a non-const object and changing a non-const reference.

But if we want to let someone know about the month but not let them change whether my birthday occurs during it we can pass a const reference.



void LookAtTheMonth(const Month &month)
{
    month.HasMyBirthday() = true;  // Compiler error: calling non-const method on const object
}


Notice that it would also be illegal to write



void LookAtTheMonth(const Month &month)
{
    if(month.HasMyBirthday())  // Compiler error: still calling a non-const method on a const object
    {
        std::cout << "Happy birthday!
";
    }
}


For this reason it’s common to overload the function so there’s a const version that returns a const reference and a non-const version that returns a non-const reference



class A
{
    private:
        std::string mString;
    public:
        std::string &GetString() { return mString; }
        const std::string &GetString const { return mString; }
};
 
A anInstance;
anInstance.GetString();  // The compiler will call the first overload since we have a non-const object
const A& constRef = anInstance;
anInstance.GetString();  // The compiler will call the second overload since we have a const object