0% found this document useful (0 votes)
19 views4 pages

C++ Programming Basics Guide

The document outlines lessons on C++ programming, covering topics such as the differences between compilers and interpreters, the importance of debugging, and the structure of functions. It explains key concepts like function parameters, return values, and variable scopes, providing examples and best practices for coding. Additionally, it includes shortcuts for commenting code and a sample program demonstrating function usage.

Uploaded by

mandoxz927
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views4 pages

C++ Programming Basics Guide

The document outlines lessons on C++ programming, covering topics such as the differences between compilers and interpreters, the importance of debugging, and the structure of functions. It explains key concepts like function parameters, return values, and variable scopes, providing examples and best practices for coding. Additionally, it includes shortcuts for commenting code and a sample program demonstrating function usage.

Uploaded by

mandoxz927
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

LEARN C++

LESSON 0.2

Learnt:
Compiler vs interpreter
Portability
High-level vs low level

LESSON 0.4

Debugging is very important to learn


Spend more time coding to reduce debugging time
name main entry point as [Link]

LESSON 0.5

Refreshed basic about Linker/Compiler.. how they work.

LESSON 0.7

Build compiles all modified code files in the project or workspace/solution, and
then links the object files into an executable. If no code files have been modified
since the last build, this option does nothing.
Clean removes all cached objects and executables so the next time the project is
built, all files will be recompiled and a new executable produced.
Rebuild does a “clean”, followed by a “build”.
Compile recompiles a single code file (regardless of whether it has been cached
previously). This option does not invoke the linker or produce an executable.
Run/start executes the executable from a prior build. Some IDEs (e.g. Visual
Studio) will invoke a “build” before doing a “run” to ensure you are running the
latest version of your code. Otherwise (e.g. Code::Blocks) will just execute the
prior executable.

LESSON 0.8

Second, add the following code at the end of your main() function (right before the
return statement):

std::[Link](); // reset any error flags


std::[Link](std::numeric_limits<std::streamsize>::max(), '\n'); // ignore any
characters in the input buffer until we find an enter character
std::[Link](); // get one more char from the user

ACTUAL C++

LESSON 1.1 - COMMENTS

In code blocks shorcut for commenting and uncommenting selection are:-


comment out :- SHIFT + CTRL + C
uncomment out :- SHIFT + CTRL + X

EXAMPLE:#

#include <iostream>
int main() {
// std::cout << "This course sucks!" << std::endl;
std::cout << "Amazing course so far <3" << std::endl;

return 0;
}

LESSON 2.1 - FUNCTIONS:

-Function are a reusable block of code that do a specific action.


-When a function is called, the current execution is paused and the function is
executed.
-The part that calls a function is called the caller and the function the callee.
-Function definition syntax is: returnValue functionName() {functionBody}.
-Functions can be called as much as we need them to.
-A function can be called inside others function but not defined in them (c++
doesn't support nested function definition).

LESSON 2.2 - RETURN FUNCTIONS

Key points:

There are two types of functions: ones that return a value (in which case the
return type must be define) and those that don't (value type of void).

Function's return value can only be a single element (no necessarily a literal but
anything the user want; expression, variables, others functions, etc as long it's a
unique element).

Functions allows us to apply the DRY philosophy which reduce redundancy and make
our code less error prone.

The main function's return value is set to 0 by default (which is his status code
indicating if the execution went well) but it's best practice to manually add a
return value for consistency with others functions.

LESSON 2.3 - RETURN FUNCTIONS

A function that does not return a value is called a non-value returning function
(or a void function).

Functions that doesn't return a value are called non-value returning function (or
void functions).

Adding an empty return statement to a void function will compile but is not needed
since this is already implicitly by the compiler.

Void functions cannot be used in places that expect a value (common sense).

returning a value from a void function will causes a compile error.

LESSON 2.4 - INTRODUCTION TO FUNCTION PARAMETERS AND ARGUMENTS

-Functions can return values to the caller.

-Parameters, declared in the function header, receive values from the caller as
arguments.

-Values are passed by value, meaning a copy is made for the function.
-Return values can be used directly as arguments in other function calls.

-Unused parameters can be omitted or left unnamed to avoid warnings.

LESSON 2.5 - LOCAL VARIABLES

When a variable is needed within a function:

-Use a function parameter when the caller will pass in the


initialization value for the variable as an argument.
-Use a local variable otherwise.

My understanding:

There are two scope (space) where identifier can live: local and global.

A scope determine where an identifier can be seen, accessed and used.

An identifier's lifetime start at his definition and end when it's scope ends
(closing curly brackets of his scope).

A return value return a temporary object and such object are destroyed when the
expression that created them ends.

Identifiers created globally can be accessed by any functions but those created
locally are bound to their scope.

Two identifier can have the same name if they don't live in the same scope.

LESSON 2.7 - FORWARD DECLARATIONS AND DEFINITIONS

// This program recives four numbers from the user and prints them them into a
complicated expression, and then solves it.
#include <iostream>

// Declaring the functions ahead of time, as this is all made for a [Link]
test in lesson 2.7.
int getValueFromUser();
int doMath(int first, int second, int third, int fourth);

// We create four variables to pass through a math function, and print for the
output.
int main()
{
// Creates four variables, as they need to be printed later.
std::cout << "Enter four numbers to do math! \n";
int first{ getValueFromUser() };
int second{ getValueFromUser() };
int third{ getValueFromUser() };
int fourth{ getValueFromUser() };

// Prints the math equasion, as otherwise the final number makes no sense.
std::cout
<< first << " + " << second << " x " << third << " / " << fourth << " =
"
<< doMath(first, second, third, fourth) << '\n';
return 0;
}

// Does complicated math for seemingly no reason. Don't blame me, I didn't request
this.
int doMath(int first, int second, int third, int fourth)
{
return first + second * third / fourth;
}

// This function requests integer input from the user, and then returns the value
for later use.
int getValueFromUser()
{
// This block of code creates a variable when requesting user input, so that
the function can be reused in the future.
std::cout << "Enter one integer: ";
int input{};
std::cin >> input;

// This returns the variable 'input' so that it can be used in the main
function.
return input;
}

Common questions

Powered by AI

Function overloading in C++ allows multiple functions to have the same name with different parameter lists, enabling them to handle different data types or a different number of parameters. This offers flexibility and can enhance code readability and usability by centralizing related operations under a single name. However, it also increases complexity, as distinguishing between overloaded functions requires careful consideration of parameter types and numbers. Explicit function declarations, although less flexible in terms of name reuse, provide clarity by reducing the possibility of ambiguity. They ensure that the function's intent and requirements are directly known from its declaration, minimizing potential confusion ."

Forward declarations in C++ are used to declare functions before they are defined, enabling the function prototypes to be known to the compiler at the point of usage even if the functions are defined later in the code. This helps to organize code more logically by separating the declaration of interfaces from the definition of implementations, which improves readability. It allows programmers to follow a top-down approach where the main function can call functions that are defined later in the file, maintaining a cleaner and more understandable code layout ."

Using a return statement in void functions in C++ is unnecessary, since void functions do not return values. If a function is defined to return void but attempts to return a value, it will cause a compile error because the function's return type has been explicitly defined as returning nothing. Including a return statement without a value, while it will compile, adds no functional value and can confuse readers by implying that control is being transferred in a manner similar to value-returning functions, which is not the case ."

Input validation and buffer clearing are crucial for making C++ programs robust by preventing invalid or unexpected data from causing errors or undefined behavior. Using std::cin.clear() resets error flags on input streams, ensuring that future input operations are not erroneously affected by past errors. Additionally, std::cin.ignore() discards invalid inputs remaining in the buffer until a specific delimiter is reached, such as a newline character, thereby preventing them from interfering with subsequent input operations. This standard strategy ensures that the program can handle input reliably and maintain data integrity ."

Compiling a single code file in C++ involves recompiling just that particular file, which does not involve invoking the linker or producing an executable, essentially creating object files from source files. Building, on the other hand, compiles all modified code files in the project or workspace, links the object files together, and generates an executable. If no files have been modified, building does nothing. The sequence can be altered: 'build' compiles and links, while 'clean' removes all cached objects and executables, ensuring all files are recompiled on the next build. 'Rebuild' combines a clean and a build step ."

It's considered best practice to manually add a return statement to the main function for consistency with other functions, which typically require a return value to signify successful execution. While the return value of the main function defaults to 0, indicating successful execution, explicitly writing 'return 0;' ensures clarity and consistency across different functions and enhances code readability, making the coding style uniform .

In C++, the scope of a variable determines where it can be accessed or modified, and its lifetime determines how long it persists in memory. Local variables are defined within a block or function and can only be accessed within that scope, ceasing to exist after the block is exited. This encapsulation ensures that data is not inadvertently accessed or changed outside its intended context, preserving modularity and reducing side effects. Global variables, however, are defined outside functions and can be accessed throughout the program, persisting for the program's lifetime. While convenient, excessive use of global variables can lead to tight coupling and unintended interactions between different parts of a program ."

The 'compile' option in C++ IDEs is used to recompile a single source file without linking or producing an executable, which is useful for quickly testing changes in a specific file without reprocessing the entire project. This is advantageous when working on large projects where compiling all files can be time-consuming. 'Build', however, compiles all modified files and links them, producing an executable. It ensures that all parts of the project are up-to-date and linked properly into a working executable, which is essential before executing the program. Using 'build' ensures that all dependencies and changed files are accounted for, reducing runtime errors ."

In C++, parameters are declared in the function header and act as placeholders for the arguments, which are the actual values passed during the function call. Parameters receive these values, and their role is to provide the means for passing input into the function. Passing by value means that a copy of the argument's value is made, and any modifications to the parameter within the function do not affect the original argument. This ensures that changes within a function do not impact the data outside of its scope, thus promoting data safety and integrity ."

Using functions in C++ supports the DRY (Don't Repeat Yourself) principle by allowing code to be reused and organized into blocks that perform specific actions. A function can be called multiple times within a program without having to rewrite the code, thus reducing redundancy and the potential for errors. Functions encapsulate behaviors into defined blocks, which can be called as needed without duplicating code, making maintenance and updates more centralized and efficient .

You might also like