Cool c++ tricks

imported_vr6

Platinum Member
Jul 6, 2001
2,740
0
0
Hey guys...does anyone know any cool shortcuts or tricks in c++? One good example is the ? and the : work in conjunction to produce the same code as in if and else statements, all in one line. If anyone knows anything could you let me know about it and maybe have a code for the example? This is for my extra credit assignment in class. Thanks!!
 

lozina

Lifer
Sep 10, 2001
11,711
8
81
how bout the most obvious shortcut that the language is named after: <variable>++
i.e. x++ instead of x = x + 1
 

igowerf

Diamond Member
Jun 27, 2000
7,697
1
76
Since we're just listing off some common shortcuts.... what about this:

bool coolTrick = true;

if (cool)
{
bla bla bla;
}

I thought it was cool when I learned about it in AP computer science. I used to do if (cool == true)... :eek: Not much of a trick though. ;)
 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
Ternary? It's not even really the same, it returns the value of one of two expressions based on a condition, that's it. if/else can have anything in the blocks.

foo = (a > 0 ? a : b); is cool, but (a > 0 ? connect(); while(foo=blah()) bar(); disconnect(); : return 0) isn't. :p

And really, everything mentioned has just been C-isms, C++ is all about OOP, so you should be talking about OOP "tricks." :)
 

imported_vr6

Platinum Member
Jul 6, 2001
2,740
0
0
ok how about this, some coding tricks/shortcuts that are in c++, not the theory of OOP. Thanks for the input so far!, but those aren't exactly extra credit worthy :D I was thinking of stuff prgrammers use that aren't taught in the classroom:beer: Thanks!
 

Ligoc

Junior Member
Apr 20, 2002
20
0
0
We used this in ap comp sci to freeze someone's computer:

double *pnum;

while(true)
{
pnum = new double;
}
 

Descartes

Lifer
Oct 10, 1999
13,968
2
0
What kind of "tricks" are you talking about? As noted, the ternary conditional operator isn't a trick; a trick is usually idiomatic to the language. An example might be the following:

int a[4] = { 1, 2, 3, 4 };
int *p = a;
a[3] = 1;
*(p + 3) = 2;

*(p + 3) is idiomatic for a[3].

Most programmers avoid less common idioms because they serve little purpose other than to obfuscate the codebase and annoy other programmers.

 

Armitage

Banned
Feb 23, 2001
8,086
0
0
Like most of this stuff, it isn't really a trick, but I find many people don't use or even know about the assert macro.
I put asserts all over the place to keep things honest during development, then a simple -DNDEBUG in the makefile to get the speed back.
 

MrChad

Lifer
Aug 22, 2001
13,507
3
81
You can use __FILE__ and __LINE__ to output the .cpp filename and line number, respectively. I'm not a C++ expert; I believe these are preprocessor directives.
 

Descartes

Lifer
Oct 10, 1999
13,968
2
0
I use asserts pretty liberally. I usually use them to enforce preconditions:

void foo(int *p, char *c)
{
ASSERT(p != NULL);
ASSERT(c != NULL);
// body
}

Of course, it's been a while since I've used asserts as I favor languages with SEH. I therefore do something like the following:

void foo(Foo f, int c)
{
if (f == null) throw new ArgumentNullException("...");
if (c < 0) throw new ArgumentOutOfRangeException("...");
// body
}

Even better are interception techniques of Aspect-Oriented Programming (AOP) using a declarative syntax to annotate method definitions. e.g. in C#:

[Requires("f != null")]
[Requires("c >= 0")]
void foo(Foo f, int c)
{
// body
}

Then again, we could all just use Eiffel and its design-by-contract facilities and get all of this for free?

 

Armitage

Banned
Feb 23, 2001
8,086
0
0
I generally only use asserts for stuff that could be screwed up explicitly by the developer ... like a enforcing a size of 3 on vectors passed to a cross-product function for example. So once you run the code a few times, you know its safe. For stuff like validating input data, checking status of files & streams, convergence of algorithms, etc. I don't use assert because that has to stay active in the production code.
 

MrChad

Lifer
Aug 22, 2001
13,507
3
81
[Requires("f != null")]
[Requires("c >= 0")]
void foo(Foo f, int c)
{
// body
}

Is this equivalent to your second example? What happens if the conditions are not met? Is a generic exception thrown?

Very interesting ... I've never seen that syntax used before.
 

Armitage

Banned
Feb 23, 2001
8,086
0
0
Originally posted by: MrChad
You can use __FILE__ and __LINE__ to output the .cpp filename and line number, respectively. I'm not a C++ expert; I believe these are preprocessor directives.

heh ... didn't know that one. Could be useful sometimes I guess.
 

Descartes

Lifer
Oct 10, 1999
13,968
2
0
Originally posted by: MrChad
[Requires("f != null")]
[Requires("c >= 0")]
void foo(Foo f, int c)
{
// body
}

Is this equivalent to your second example? What happens if the conditions are not met? Is a generic exception thrown?

Very interesting ... I've never seen that syntax used before.

Functionally equivalent, yes. You can, in most cases, define which exception is thrown.

The difference is that the above syntax is not part of the method definition; it's metadata, like it should be for enforcing preconditions.
 

manly

Lifer
Jan 25, 2000
13,258
4,033
136
Originally posted by: MrChad
You can use __FILE__ and __LINE__ to output the .cpp filename and line number, respectively. I'm not a C++ expert; I believe these are preprocessor directives.
Those are C preprocessor directives, one of the (only?) actual tricks revealed in this thread.
that's not really a trick...
Heh, that's my general opinion of this thread. Any ANSI C book will cover the C++ operators, so they aren't worth repeating.
 

imported_vr6

Platinum Member
Jul 6, 2001
2,740
0
0
haha sorry, maybe my title is misleading. I am in a cmsc202 class - Intro to c++ programming. SO basically i am asking for stuff that a c++ newbie wouldn't now about. so far most of the stuff said are brand new, so i have to try them out. Thanks for the help, keep them coming if u all have more :)
 

BFG10K

Lifer
Aug 14, 2000
22,709
3,003
126
A = A + 5 becomes A += 5.
B = B - C becomes B -= C.

Any of the standard binary arithmetic operators will work like that.
 

Armitage

Banned
Feb 23, 2001
8,086
0
0
Here's one I use sometimes...
To pause a program during execution for debugging, put in a line like this:

cin >> i; ///i is an integer.

Now the program will stop to wait for input everytime you hit that line.
You type a number & hit enter to continue. It will pause everytime it gets to that line or another like it

Thats not the trick.

The trick is, if you don't want it to pause at those lines anymore, and just want to continue, enter a letter instead of a number. That will crash the input stream, and that line won't stop the program anymore. Of course you can't use cin anymore either unless you reset it.
 

Descartes

Lifer
Oct 10, 1999
13,968
2
0
Originally posted by: manly
Originally posted by: MrChad
You can use __FILE__ and __LINE__ to output the .cpp filename and line number, respectively. I'm not a C++ expert; I believe these are preprocessor directives.
Those are C preprocessor directives, one of the (only?) actual tricks revealed in this thread.

How in the world are those tricks? They're preprocessor definitions, hardly a trick; on top of that, they're ANSI standard. If you can easily find them in the documentation, they're not really a trick.
 

Descartes

Lifer
Oct 10, 1999
13,968
2
0
Here's another common idiom of the C language:

int x = 1, y = 2;
x ^= y;
y ^= x;
x ^= y;

It's a "trick" because it's idiomatic to the C language; it's not a simple operator/preproc def/etc. that you can find in the documentation. Most C programmers immediately know what it is when they see it, but those that don't know C do not.
 

imported_vr6

Platinum Member
Jul 6, 2001
2,740
0
0
You can use __FILE__ and __LINE__ to output the .cpp filename and line number, respectively. I'm not a C++ expert; I believe these are preprocessor directives.

can someone elaborate on that alittle more? i am not sure what it means, i did find it on google, but not a very well explanations. perhaps a short code example?

from google..

__LINE__
If the compiler encounters a variable with the name __LINE__ in the source then it replaces that variable with the number of the line being compiled at that moment. This can be useful for debugging Prolog programs as __LINE__ can be used by debug predicates that write and/or log messages of a Prolog application.


__FILE__
If the compiler encounters a variable with the name __FILE__ in the source then it replaces that variable with the name of the file being compiled at that moment. This can be useful for debugging Prolog programs as __FILE__ can be used by debug predicates that write and/or log messages of a Prolog application.
 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
If you have a file called foo.cc, and on line 10 you put cout << __FILE__ ": line " __LINE__ <<endl;, compiled and ran it, whenever the code reached what's on line 10, you would see:

foo.cc: line 10
 

arcain

Senior member
Oct 9, 1999
932
0
0
Originally posted by: Descartes
What kind of "tricks" are you talking about? As noted, the ternary conditional operator isn't a trick; a trick is usually idiomatic to the language. An example might be the following:

int a[4] = { 1, 2, 3, 4 };
int *p = a;
a[3] = 1;
*(p + 3) = 2;

*(p + 3) is idiomatic for a[3].

Most programmers avoid less common idioms because they serve little purpose other than to obfuscate the codebase and annoy other programmers.

And...

*(3 + p) is equivalent to *(p + 3)...

which means 3[a] is equivalent to a[3].