Are you local? Or global? private or public?
// Struct members are default public
struct x {
int a;
float b;
char c[10];
};
// class members are default private
class z {
int a;
float b;
char c[10];
public:
int getvalue() const;
void setvalue( int v );
};
Conditionals
#include <iostream>
#include <cstdio>
#include <cstdint>
int main()
{
const int ZERO = 0;
const int ONE = 1;
const int TWO = 2;
const int THREE = 3;
int x = 42;
int y = 73;
if ( x < y ) {
} else if ( y > x ) {
} else {
}
// ternary
printf ("This number is greater : %d\n", x > y ? x : y );
switch (x) {
case ZERO: cout << ZERO << endl; break;
case ONE: cout << ONE << endl; break;
case TWO: cout << TWO << endl; break;
case THREE: cout << THREE << endl; break;
case 42: cout << 42 << endl; break;
case 52: cout << 52 << endl; break;
default: cout << 99 << endl; break;
}
}
Loops
#include <iostream>
#include <cstdio>
int main() {
int array[] = { 1,2,3,4,5 };
char string[] = "string";
auto j = 3;
for( auto i : array ) {
printf( "i is %d\n", i );
}
// c++ range based loop
// range based loop is a compile time feature so compiler knows the size and type
for ( int i : array ) {
printf( "* %d / ", i );
}
printf( "\n" );
// for ( char c : "abcdef" ) { // this works too!!
// for ( char i : string ) { // this works too!!
for ( int i : string ) { // int works with char too!!
printf( "* %c / ", i );
}
printf( "\n" );
// for ( int i = 0; string[i]; i++ ) { // last char in a string is '0', == false
for ( char *cp = string; *cp ; ++cp ) {
printf( "* %c / ", *cp );
}
cout << endl;
for (int i = 0; i < j; i++) {
}
int i = 0;
while (i < 5) {
if ( i == 2 ) {
i++; // important!!
continue;
} else if ( i == 3 ) {
break;
}
i++;
}
do {
i--;
} while ( i > 0 );
}
Functions
#include <cstdio>
#include <iostream>
#include <string>
using namespace std;
using std::cin;
using std::cout;
void func( const string * fs )
{
printf( "value is %s\n", fs->c_str());
}
int main( int argc, char * argv[] )
{
string s = "hello im a string";
puts( "this is main()" );
func(&s);
printf( "string is %s\n", s.c_str());
for (int i=0; argv[i]; i++ ) {
printf( argv[i] );
printf( "%d: %s\n", i, argv[i] );
}
return 0;
}
Using namespace or else
#include <cstdio> #include <iostream> #include <string> using namespace std; // Another way #include <cstdio> using std::puts; using std::printf; #include <iostream> using std::cin; using std::cout;
No comments:
Post a Comment