There are always few little known or hidden features in each programming language. AT StackOverflow.com someone started a series of posts “Hidden features of” programming languages. The Hidden Features series is great for people who are new to a certain language.

I have collected few of the features of both C and C++ here.

Like the ternary operator; most of the programmers are familiar with.
[code=’c’]x = (y < 0) ? 10 : 20; [/code] However this can be used the other way. [code='c'](y < 0 ? x : y) = 20;[/code] i.e. [code='c']if (y < 0) y = 20; else x = 20; [/code] Another feature is Resource Acquisition Is Initialization (RAII) which is often ignored by the programmers coming from non object oriented world i.e. C background.

Can you write a return statement in a function that returns void?
[code=’c’] static void foo (void) { }
static void bar (void) {
return foo(); // Note this return statement.
}
int main (void) {
bar();
return 0;
}[/code]
Even you could write something like

[code=’c’]static void foo() { return (void)”i’m discarded”; }[/code]

The comma operator isn’t widely used. It can certainly be abused, but it can also be very useful. One of the most common use is
[code=’c’]
for (int i=0; i<10; i++, doSomethingElse()) { /* whatever */ } [/code] C99 has some awesome any-order structure initialization. [code='c']struct foo{ int x; int y; char* name; }; void main(){ foo f = { .y = 23, .name = "awesome", .x = -38 }; } [/code]

2 Shares
Share1
+1
Tweet
Share
Stumble1