Skip to content

Instantly share code, notes, and snippets.

@simplytunde
Last active August 29, 2015 14:12
Show Gist options
  • Save simplytunde/eff827503a82ae324602 to your computer and use it in GitHub Desktop.
Save simplytunde/eff827503a82ae324602 to your computer and use it in GitHub Desktop.
C++: Basic Types Gotchas

Basic Types Gotcha

  • If you assign out of range value to signed type, the result is undefined
  • The code below will never terminate because --0 for unsigned int wraps around to become positive
for (unsigned u = 10; u >= 0; --u)
    std::cout << u << std::endl;
  • If combine unsigned and signed in a expression,everything get converted to unsigned. For example,
   unsigned int a=1;
   int b=-1;
   cout<<(a*b)<<endl; //This will not print out -1 as expected
  • A string literal is an array of constant characters with \0 appended to the back. For example, the length of "A" is 2 instead of 1 since \0 is appended to the back.
  • For the string literal "Hi \x4dO\115!\n"(This prints out MOM), c++ assume the first 3 numbers after \ represents a letter and assume hexdecimal after \x representd a letter also.
  • If you try to assign double to int using list initialization, c++ will raise error unlike if you use equal to.
  • variable inside func are not default initliazed.
  • You can declare a variable more than once using extern keyword but must define just once.
  • Avoid identifer that starts with double underscore, underscore & uppercase or just underscore.
  • Define variable close to where you will use it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment