Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.
Code:
z = z =1;

You meant:
Code:
z = z + 1
or
Code:
z++;

There's no reason NOT to have the preincrement and postdecrement in the if condition, it is just a bit obtuse. In the if and else, in the print statements, you may want to print y+1 instead of y, since that will be the value when the if is evaluated. That would make more sense to me, at least. This is changing the behavior of the original code, but the behavior of the original was silly, IMO.

-Lee
 
Ooops, thanks for the catch. I fixed it.

Is this what you had in mind? I do want to learn the difference between well thought out code, and code that works but needs improvement. :)

Code:
/*
 *  program3.cpp
 *  
 *
 *  Created by [redacted] on 11/14/09.
 *  Copyright 2009 __MyCompanyName__. All rights reserved.
 *
 */

#include<iostream>

using namespace std;

int main( int argc, char *argv[] )

{
	int x = 1, y = 3, z = 4;
	int *num;
	const float pi = 3.14;
	z*=y;
	y = x + (int)pi;
	num = &y;
	
	z = z =1;
	if( z <= y ) {
		y = y-1;
			cout << "Z: " << z << " <= Y+1: " << y << endl; 
	} else {
		y = y-1;
			cout << "Z: " << z << " > Y+1: " << y << endl;
	}
		
		cout << "Z: " << z << endl;
		cout << "Y: " << y << endl;
		cout << "The base memory address of Y: " << num << endl;
		cout << "The value pointed to by num: " << *num << endl;
		
		return 0;
		
}

Code:
Z: 1 <= Y+1: 3
Z: 1
Y: 3
The base memory address of Y: 0xbffffa9c
The value pointed to by num: 3
 
Saying you're printing Y+1 doesn't mean you are =). I would just say you're printing Y, and print y+1. I am saying this because the impression one gets from the print statements is *why* that statement is being printed, which is why i think it's best to print the value when the if was evaluated. Certainly it is a lie to say that y is its previous value, but i'm not that interested in the current value of y in this case. In fact, it would be just as well to decrement y after the if and else if you'd rather print what y was during the comparison.

When i was writing the explanation previously, i was writing something that would result in the same behavior as the original, but divided up the steps so they were (hopefully) more clear. That's why i stuck the y - 1 in both the if and else.

To design this code well, you need to know what you're trying to do. If you're just trying to learn C++ syntax, there is no good design here. Reading and understanding any piece of code will get you closer to that goal, even if it's nonsensical. Learning why it's nonsensical is what counts.

-Lee
 
Well, I'm going to have to think on it a while. I'm sure you're right, that it doesn't matter so much when you are learning syntax.
 
I just worked with the first copy of the code you posted. Since the values are fixed, there's no input, etc. you can pare it down to this:
Code:
#include<iostream>

int main( int argc, char *argv[] ) {
	int y = 3;
	int *num = &y;
	std::cout << "Z: 13 > Y: 3" << std::endl << "Z: 13" << 
		std::endl << "Y: 3" << std::endl << 
		"The base memory address of Y: " << num << std::endl << 
		"The value pointed to by num: 3" << std::endl;
	return 0;
}

The only part of this program that wasn't completely fixed was the memory address of a variable. I left the initialization to 3 for y, but it's not necessary.

The rest of it is always going to go exactly the same way, and produce exactly the same output.

You may want to move on to another example. The only thing to really understand from this one, as far as I can see, is the use of a pointer to reference a position in memory, and the preincrement and postdecrement. If you understand those, move on. If you don't, what's confusing about them?

-Lee
 
So sorry I haven't responded...been really busy with chemistry these days.

I'll have a look through that example and get back, hopefully tonight. :)
 
OK, that chem is keeping me busy, but I had time to move to another example the other day.

Code:
/*
 *  program7.cpp
 *  
 *
 *  Created by [redacted] on 11/26/09.
 *  Copyright 2009 __MyCompanyName__. All rights reserved.
 *
 */

#include <iostream>

using namespace std;

int main( int argc , char *argv[] ) {
	
	int number ;
	
	cout << "Enter an integer: " ;
	cin >> number ;
	
	if( number % 2 == 0 ) {
	cout << number << " is even." << endl;
	} else {
	cout << number << " is odd." << endl;
	}
		
	return 0;
}

This one went down smoothly, so to speak. As best as I can tell, this code takes a user-supplied integer, and determines if the remainder when divided by 2 is zero (number % 2 is equal to 0). If yes, the number is even. Else, the number is odd. I think that makes good sense. :D

Anything you guys would like to point out here before I move on to another example?

BTW, I obtained an older book called C++ From The Ground Up by Herbert Schildt from a friend. It's old, but I think at this point it will be better than internet-based tutorials.
 
As far as I can tell this is just to give you a modulus example, and it looks fine. It's not important, but:
Code:
if((x & 1) == 0) {
  //even
} else {
  //odd
}

is probably a bit faster. In practice it likely doesn't matter, but modulus requires a divide which is "costly", while a bitmask is "cheap". You should rarely need to worry about this, but I like to know what's really happening.

-Lee
 
As far as I can tell this is just to give you a modulus example, and it looks fine. It's not important, but:
Code:
if((x & 1) == 0) {
  //even
} else {
  //odd
}

is probably a bit faster. In practice it likely doesn't matter, but modulus requires a divide which is "costly", while a bitmask is "cheap". You should rarely need to worry about this, but I like to know what's really happening.

-Lee

I am pretty sure that any modern compiler would optimize %2 to a bit shift instead of doing a division. Aside from that, I am now actually curious as of how modulus works in a processor. I know that doing a devision in x86 assembly stores the result in one register and the remainder in another, but is there a way to get just the remainder if you want to?

As for the OP, i found this tutorial a tremendous help when I was learning C++. The site has also very good documentation for functions in the standard libraries.
 
Hey guys,

As I said before, I obtained an older C++ book from a friend. However, it shows its age because I've had to do some slight rewriting of the examples to make them work. I know a new book is better, but I haven't gotten around to it thanks to school. Any suggestions there would be most helpful. :)

Anyhoo, the current book is helping me better understand things; much better than most of the internet resources I've seen.

This one example of returning a value caused a few problems:

Code:
/*
 *  return.cpp
 *  
 *
 *  Created by [redacted] on 12/18/09.
 *  Copyright 2009 __MyCompanyName__. All rights reserved.
 *
 */

//Returning a value

#include <iostream.h>

mul(int x, int y); //mul's prototype

main()
{
	int answer;
	
	answer = mul(10, 11); //assign return value
	cout << "The answer is " << answer;
	
	return 0;
}

//This function returns a value

mul(int x, int y)
{
	return x * y; //return product of x and y
}

Obviously, some rewrite was required:

Code:
/*
 *  return.cpp
 *  
 *
 *  Created by [redacted] on 12/18/09.
 *  Copyright 2009 __MyCompanyName__. All rights reserved.
 *
 */

//Returning a value

#include <iostream>

using namespace std;

mul(int x, int y); //mul's prototype

main()
{
	int answer;
	
	answer = mul(10, 11); //assign return value
	cout << "The answer is " << answer;
	
	return 0;
}

//This function returns a value

mul(int x, int y)
{
	return x * y; //return product of x and y
}

However, despite what the books says about int being the assumed default if no type is declared, it still did not compile.

Code:
return.cpp:16: error: expected constructor, destructor, or type conversion before ‘;’ token
return.cpp: In function ‘int main()’:
return.cpp:22: error: ‘mul’ was not declared in this scope
return.cpp: At global scope:
return.cpp:30: error: ISO C++ forbids declaration of ‘mul’ with no type

After declaring int, it works as expected. Are you indeed now not allowed to leave a variable undeclared and have it assumed to be an int?

Code:
/*
 *  return.cpp
 *  
 *
 *  Created by [redacted] on 12/18/09.
 *  Copyright 2009 __MyCompanyName__. All rights reserved.
 *
 */

//Returning a value

#include <iostream>

using namespace std;

int mul(int x, int y); //mul's prototype

main()
{
	int answer;
	
	answer = mul(10, 11); //assign return value
	cout << "The answer is " << answer;
	
	return 0;
}

//This function returns a value

int mul(int x, int y)
{
	return x * y; //return product of x and y
}
Code:
The answer is 110
 
It's just that the C89 standard requires that 'main' returns an 'int', so compilers provide feedback that you forgot to meet that requirement.

And yes functions must declare their returns types.
 
It's just that the C89 standard requires that 'main' returns an 'int', so compilers provide feedback that you forgot to meet that requirement.

And yes functions must declare their returns types.
OK, thanks. The book does indeed say that one can explicitly declare int; that must have been made the standard since then. I'll keep that in mind as I plow ahead...
 
One thing I have found very handy is my O'reilly pocket references. I have one for C and Java and my Dad has one for Objective-C and they are in constant use. I'd recommend getting one for C++ as they enable you to find answers to questions without searching the internet high and low. They also tend to be quite good quality - plus they only cost about £5, bargain!

Oh yes, those pocket references are great, I've got one for Java, Python, and Obj-c
 
Bruce Eckel makes his book "Thinking in C++" available as a PDF download free of charge in hopes you'll buy his print version. His books were done based on feedback gleaned form students of his payed seminars.
 
Hey all,

Just wanted to let those that helped me know that I haven't forgotten about programming. Haven't had much time for it lately, but I've picked C++ back up again today and I amazed myself with how little I had forgotten. Still working through that old book.
 
Don't mind if you keep the examples coming! I myself am learning the language as well. I've taken a class and have some of the basics down, but am now exploring more powerful tools such as recursion, multiple inheritance, polymorphism, templates, etc.

I'd be glad to help where I can, and learn new things as well.
 
Don't mind if you keep the examples coming! I myself am learning the language as well. I've taken a class and have some of the basics down, but am now exploring more powerful tools such as recursion, multiple inheritance, polymorphism, templates, etc.

I'd be glad to help where I can, and learn new things as well.

I will be after I get back up to speed a little more. :cool:
 
OK, back to the grindstone. :) Working on blocks.

I've run into a baffling issue with an example in my book. Please note that this is not the original; I added the a > b and a = b blocks. Here's the code:

Code:
/*
 *  blocks.cpp
 *  
 *
 *  Created by [redacted] on 2/9/10.
 *  Copyright 2010 __MyCompanyName__. All rights reserved.
 *
 */

//This program demonstrates blocks of code

#include <iostream>

using namespace std;

main()
{
	int a, b;
	
	cout << "enter first number: ";
	cin >> a;
	cout << "enter second number: ";
	cin >> b;
	
	if(a < b) {
		cout << "First number is less than second.\n";
		cout << "Their difference is: " << b-a;
	}	
	
	if(a > b) {
		cout << "First number is greater than second.\n";
		cout << "Their sum is: " << a+b;
	}	
	
	if(a = b) {
		cout << "First number equals second.\n";
		cout << "Their product is: " << a*b;
	}		
	
	return 0;
}

The weird thing is that if int a, b are different numbers (say 4 and 5), the first block's condition is satisfied and it runs. However, it also takes the square of b!!

Code:
$ ./output
enter first number: 4
enter second number: 5
First number is less than second.
Their difference is: 1First number equals second.
Their product is: 25

Am I missing something about using more than one block?
 
This is a typical beginner mistake in that 'a' is being assigned the value of 'b'. The if then evaluates to true for any value of 'b' that is non zero.

Code:
	if(a = b) {

should be changed as follows to perform a test of equivalence:

Code:
	if(a == b) {
 
= is assignment. An assignment is a binary operator, which evaluates to its right operand. If the right operand is non-zero, and you evaluate as a condition it will be true.

== is equivalence. It is also a binary operator, but only evaluates to true if its left and right operands are equal.

You are using one of these. You meant to use the other.

-Lee

edit: lloyddean beat me this time.
 
This is a typical beginner mistake in that 'a' is being assigned the value of 'b'. The if then evaluates to true for any value of 'b' that is non zero.

Code:
	if(a = b) {

should be changed as follows to perform a test of equivalence:

Code:
	if(a == b) {
OK, big DUH moment here. I knew that. :eek: Sometimes, it takes someone else to spot your mistakes. Thank you, both. :) == it is!
 
Yep, it surely works perfectly. I appreciate you guys taking the trouble to help me out, spotting little things like this. Won't make that mistake again.
 
Won't make that mistake again.

Oh, yes you will. At the worst possible moment. I am not a professional programmer, but after years of programming I still sometimes forget the second =. I am pretty sure that everyone does. It happens very rarely, but when it does you don't get a compilation error. You only get obviously wrong results and in a sufficiently complex program the cause could be in a million different places, so I hope you like debugging.

A trick that some people do is to reverse the order of the comparison. So instead of 'if(a==4)', you would write 'if(4==a)'. Now if you forget the second = the compiler will get 'if(4=a)' and will throw an error (this works only if you compare with constants). I personally don't like this, since I find it decreases the code readability, but you may find it useful.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.