-
Statements and flow control
A simple C++
statementis each of the individual instructions of a program, always end with a semicolon(😉, and are executed in the same order in which they appear in a program.-
Selection Statements: if and else
The if keyword is used to execute a statement or block, if, and only if, a condition is fulfilled. Its syntax is :
if (x == 100) cout << "x is 100"; if (x == 100) { cout << "x is "; cout << x; }Selection statements with if can also specify what happens when the condition is not fulfilled, by using the else keyword to introduce an alternative statement. Its syntax is :
if (x == 100) cout << "x is 100"; else cout << "x is not 100";Several
if + elsestructures can be concatenated with the intention of checking a range of values.if (x > 0) cout << "x is positive"; else if (x < 0) cout << "x is negative"; else cout << "x is 0"; -
Iteration Statements (loops)
Loops repeat a statement a certain number of times, or while a condition is fulfilled. They are introduced by the keywords
while,do, andfor.-
The while loop
The simplest kind of loop is the while-loop. Its syntax is:
while (expression) statementThe
while-loopsimply repeatsstatementwhileexpressionistrue. If, after any execution of statement, expression is no longer true, the loop ends, and the program continues right after the loop.A thing to consider with while-loops is that the loop should end at some point, and thus the statement shall alter values checked in the condition in some way, so as to force it to become false at some point.
-
The do-while loop
A very similar loop is the do-while loop, whose syntax is :
do statement while (condition);It behaves like a
while-loop, except that condition is evaluated after the execution ofstatementinstead of before, guaranteeing at least one execution of statement, even if condition is never fulfilled. -
The for loop
The for loop is designed to iterate a number of times. Its syntax is:
for (initialization; condition; increase) statement;Like the
while-loop, this loop repeatsstatementwhileconditionis true. But, in addition, thefor loopprovides specific locations to contain aninitializationand anincreaseexpression, executed before the loop begins the first time, and after each iteration, respectively.Therefore, it is eapecially useful to use counter variables as
condition.It may be useful to execute more than a single expression as any of
initialization,condition, orstatement.Range-based for loop
The for-loop has another syntax, which is used exclusively with ranges:
for (declaration : range) statement;This kind of
for loopiterates over all the elements in range, where declaration declares some variable able to take the value of an element in thisrange.Rangesare sequences of elements, including arrays, containers, and any other type supporting the functions begin and end. -
Jump statements
-
The break statement
break leaves a loop, even if the condition for its end is not fulfilled. It can be used to end an infinite loop, or to force it to end before its natural end.
-
The continue statement
The continue statement causes the program to skip the rest of the loop in the current iteration, as if the end of the statement block had been reached, causing it to jump to the start of the following iteration.
-
The goto statement
goto allows to make an absolute jump to another point in the program. This unconditional jump ignores nesting levels, and does not cause any automatic stack unwinding(堆栈解退).
The destination point is identified by a label, which is then used as an argument for the goto statement.
A label is made of a valid identifier followed by a colon (
:).goto is generally deemed a low-level feature, with no particular use cases in modern higher-level programming paradigms generally used with C++.
-
-
Another selection statement : switch
The syntax of the switch statement is a bit peculiar. Its purpose is to check for a value among a number of possible constant expressions. It is something similar to concatenating
if-elsestatements, but limited to constant exprssions.Its most typical syntax is :
switch (expression) { case constant1: group-of-statements-1; break; case constant2; group-of-statements-2; break; . . . default: default-group-of-statements }It works in the following way:
switchevaluatesexpressionand checks if it is equivalent toconstant1; if it is, it executesgroup-of-statements-1until it finds the break statement. When it finds thisbreakstatement, the programjumpsto the end of the entireswitchstatement (the closing brace).
-
-
-
Functions
In C++, a function is a group of statements that is given a name, and which can be called from some point of the program. The most common syntax to define a function is:
type name (parameter1, parameter2, ...) {statements}Where :
-
typeis the type of the value returned by the function -
nameis the identifier by which the function can be called -
parameters(as many as needed): Each parameter consists of atypefollowed by anidentifier, with each parameter being seperated from the next by a comma. -
statementsis the function’s body. It is a block of statements surrounded by braces {} that specify what the function actually does.
Functions with no type, The use of void
The syntax shown above for functions:
type name (argument1, argument2 ... ) {statements}Requires the declaration to begin with a type. This is the type of the value returned by the function. But what if the function does not need to return a value? In this case, the type to be used is
void, which is a special type to represent the absence of value.The
voidcan also be used in the function’s parameter list toexplicitly specify that the function takes no actual parameterswhen called.The return value of main
There is a catch: If the execution of
mainends normally without encountering areturnstatement the compiler assumes the function ends with an implicit return statement:return 0;And this only applies to function
mainfor historical reasons. All other functions with a return type shall end with a proper return statement that includes a return value, even if this is never used.Arguments passed by value and by reference
Normally modification of variables passed to a function which within the function has no effect on the values of the variables, because variables themselves not passed to the function on the call, but only copies of their values at that moment.
In certain cases, though, it may be useful to access an external variable from within a function. To do that, arguments can be passed by
reference, instead of byvalue.To gain access to its arguments, the function declares its parameters as references.
In C++, references are indicated with an
ampersand (&)following the parametertype, as in the parameters taken by function.When a variable is passed by reference, what is passed is no longer a copy, but the variable itself, the variable identified by the function parameter, becomes somehow associated with the argument passed to function, and any modification on their corresponding local variables within the function are reflected in the variables passed as arguments in the call.
Efficiency considerations and const references
Calling a function with parameters taken by value causes copies of the values to be made. This is a relatively inexpensive operation for fundamental types such as
int, but if the parameter is of a large compound type, it may result on certain overhead.But the copy can be avoided altogether if both parameters are made references (
function(string& param1, string& param2))Arguments by
referencedo not require a copy, the function operates directly on (aliases of) the strings passed as arguments, and at most, it might mean the transfer of certain pointers to the function. In this regard, the version of concatenate taking references is more efficient than the version taking values, since it does not need to copy expensive-to-copy strings.On the flip side, functions with reference parameters are generally perceived as functions that modify the arguments passed, because that is why reference parameters are actually for.
The solution is for the function to gurantee that its reference parameters are not going to be modified by this function.
Inline Functions
Calling a function generally causes a certain overhead (stacking arguments, jumps, etc…), and thus for very short functions, it may be more efficient to simply insert the code of the function where it is called, instead of performing the process of formally calling a function.
Preceding a function declaration with the
inlinespecifier informs the compiler that inline expansion is preferred over the usual funciton call mechanism for a specific function. This does not change at all the behavior of a function, but is merely used to suggest the compiler that the code generated by the function body shall be inserted at each point the function is called, instead of being invoked with a regular function call.inline string concatenate (const string& a, const string& b) { return a + b; }Most compilers already optimize code to generate inline functions when they see an opportunity to improve efficiency, even if not explicitly marked with the inline specifier. Therefore, this specifier merely indicates the compiler that inline is preferred for this function, although the compiler is free to not inline it, and optimize otherwise.
Default values in parameters
In C++, functions can also have optional parameters, for which no arguments are required in the call, in such a way that, for example, a function with three parameters may be called with only two. For this, the function shall include a default value for its last parameter, which is used by the function when called with fewer arguments.
Declaring Functions
In C++, identifiers can only be used in expressions onve they have been declared.
The same applied to functions. Functions cannot be called before they are declared. This why the functions were always defined before the
mainfunction.Recursivity
Recursivity is the property that functions have to be called by themselves. It is useful for some tasks, such as sorting elements, or calculating the factorial of numbners.
-
-
Overloads and templates
-
Overloaded functions
In C++, two different functions can have the same name if their parameters are different; either because they have a different number of parameters, or because any of their parameters are of a different type.
Two functions with the same name are generally expected to have -at least- a similar behavior.
Two overloaded functions (i.e., two functions with the same name) have entirely different definitions.
A function cannot be overloaded only by its return type. At least one of its parameters must have a different type.
-
Function templates
Overloaded functions may have the same definition(which means same statement insdie the function).
Function could be overloaded with different parameter types, but with the exact same body.
Function could be overloaded for a lot of types, and it could make sense for all of them to have the same body. For cases such as this, C++ has the ability to define functions with generic types, known as function templates.
Defining a function template follows the same syntax as a regular function, except that it is preceded by the
templatekeyword and a series of template parameters enclosed inangle-brackets <>:template <template-parameters> function-declarationThe template parameters are a series of parameters separated by commas. These parameters can be generic template types by specifying either the
classortypenamekeyword followed by an identifier. This identifier can then be used in the function declaration as if it was a regular type.template <class SomeType> SomeType sum (SomeType a, SomeType b) { return a + b; }It makes no difference whether the generic type is specified with keyword
classor keywordtypenamein the template argument list (they are 100% synonyms in template declarations).In the code above, declaring
SomeType(a generic type within the template parameters enclosed in angle-brackets) allowsSomeTypeto be used anywhere in the function definition, just as any other type; it can be used as the type for parameters, as return type, or to declare new variables of this type.In all cases, it represents a generic type that will be determined on the moment the template is instantiated.
Instantiating a template is applying the template to create a function using particular types or values for its template parameters. This is done by calling the function template, with the same syntax as calling a regular function, but specifying the template arguments enclosed in angle brackets:
name <template-arguments> (function-arguments)x = sum<int>(10, 20);The function
sum<int>is just one of the possible instantiations of function templatesum. In this case, by using int as template argument in the call, the compiler automatically instantiates a version ofsumwhere each occurrence ofSomeTypeis replaced byint, as if it was defined as :int sum (int a, int b) { return a + b; }k = sum<int>(i,j); h = sum<double>(f,g); // it is possible to instead simply write k = sum(i,j); h = sum(f,g);without the type encloed in angle brackets, Naturally, for that, the type shall be unambiguous. If sum is called with arguments of different types, the compiler may not be able to deduce the type of T auytomatically.
Templates are a powerful and versatile feature, they can have multiple template parameters, and the function can still use regular non-templated types.
-
Non-type template arguments
The template parameters can not only include types introduced by class or typename, but can also include expressions of a particular type.
// template arguments #include <iostram> using namespace std; template <class T, int N> T fixed_multiply (T val) { return val * N; } int main() { std::cout << fixed_multiply<int,2>(10) << '\n'; std::cout << fixed_multiply<int,3>(10) << '\n'; }The second argument of the
fixed_multiplyfunction template is of typeint. It just looks like a regular function parameter, and can actually be used just like one.But there exists a major difference: the value of template parameters is determined on compile-time to generate a different instantiation of the function
fixed_multiply, and thus the value of that argument is never passed during runtime: The two calls tofixed_multiplyinmainessentially call two versions of the function: one that always multiplies by two, and one that always multiplies by three. For that same reason, ***the second template argument needs to be a constant expression (it cannot be passed a variable)***.
-
-
Name visibility
-
Scopes
Named entities, such as variables, functions, and compound types need to be declared before being used in C++. The point in the program where this declaration happens influences its visibility:
AN Entity declared outside any block has global scope, meaning that its name is valid anywhere in the code. While an entity declared within a block, such as a function or a selective statement, has block scope, and is only visible within the specific block in which it is declared, but not outside it.
Variables with block scope are known as local variables.
In each scope, a
namecan only represent one entity. The visibility of an entity with block scope extends until the end of the block. Nevertheless, an inner block, because it is a different block, can re-utilize a name existing in an outer scope to refer to a different entity; in this case, the name will refer to a different entity only within the inner block, hiding the entity it names outside. -
Namespaces
Only one entity can exist with a particular name in a particular scope. This is seldom a problem for local names, since blocks tend to be relatively short, and names have particular purposes within them, such as naming a counter variable, an argument, etc…
But non-local names bring more possibilities for name collision, especially considering that libraries may declare many functions, types, and variables, neither of them local in nature, and some of them very generic.
Namespaces allow us to group named entities that otherwise would have global scope into narrower scopes, giving them
namespace scope. This allows organizing the elements of programs into different logical scopes referred to by names.The syntax to declare a namespacees is:
namespace identifier { named_entities }Where
identifieris any valid identifier andnamed_entitiesis the set of variables, types and functions that are included within the namespace.namespace myNamespace { int a, b; }In this case, the variables
aandbare normal variables declared within a namespace calledmyNamespace.These variables can be accessed from within their namespace normally, with their identifier (either
aorb), but if accessed from outside themyNamespacenamespace they have to be properly qualified with the scope operator::. For example, to access the previous variables from outsidemyNamespacethey should be qualified like :myNamespace::a myNamespace::bNamespaces are particularly useful to avoid name collisions.
Namespaces can be split: Two segments of a code can be declared in the same namespace:
namespace foo {int a;} namespace bar {int b;} namespace foo {int c;}Namespaces can even extend across different translation units (i.e., across different files of source code).
-
using
The keyword
usingintroduces a name into the current declarative region (such as a block), thus avoiding the need to qualify the name.using namespace std; using std::cout;using and using namespace have validity only in the same block in which they are stated or in the entire source code file if they are used directly in the globle scope.
// using namespace example #include <iostream> using namespace std; namespace first { int x = 5; } namespace second { double x = 3.14159; } int main() { { using namespace first; cout << x << '\n'; } { using namespace second; cout << x << '\n'; } return 0; } -
Namespace aliasing
Existing namespaces can be aliased with new names, with the following syntax:
namespace new_name = current_name; -
The std namespace
All the entities (variables, types, constants, and functions) of the standard C++ library are declared within the
stdnamespace. -
Storage classes
The storage for variables with globle or namespace scope is allocated for the entire duration of the program. This is known as static storage, and it constracts with the storage for local variables (those declared within a block).
These use what is known as automatic storage.
The storage for local variables is only avaiable during the block in which they are declared; after that, that same storage may be used for a local variable of some other function, or used otherwise.
But there is another substantial difference between variables with static storage and variables with automatic storage:
-
Variables with static storage (such as globle variables) that are not explicitly initialized are automatically initialized to zeroes.
-
Variables with automatic storage (such as local variables) that are not explicitly initialized are left uninitialized, and thus have an undermined value.
-
-
相关推荐
win2012 r2 + IIS8.5 伪静态设置脚本映射
win2012 r2 + IIS8.5 伪静态设置脚本映射,网站用的.net fromwork 2.0 ,应用程序池设置了32位支持
LINQ
Language Integrated Query From Wikipedia, the free encyclopedia Language Integrated Query Influenced by SQL, Haskell Language Integrated Query (LINQ, pronounced "link") is
3.1 计算机视觉的发展和卷积神经网络概要(百度架构师手把手带你零基础实践深度学习原版笔记系列)
3.1 计算机视觉的发展和卷积神经网络(百度架构师手把手带你零基础实践深度学习原版笔记系列) 概要 计算机视觉作为一门让机器学会如何去“看”的科学学科,具体的说,就是让机器去识别摄像机拍摄的图片或视频中的物体,检测出物体所在的位置,并对目标物体进行跟踪,从而理解并描述出图片或视频里的场景和故事,以此来模拟人脑视觉系统。因此,计算机视觉也通常被叫做机器视觉,其目的是建立能够从图像或者视频中“感知”信息的人工系统。 计算机视觉技术经过几十年的发展,已经在交通(车牌识别、道路违章抓拍)、安防(人脸闸机.
vue3 ts Type assertion expressions can only be used in TypeScript files
vue3 ts Type assertion expressions can only be used in TypeScript files
外部ADC之AD7949——14bit、8通道、250k
在实际项目中,仅靠单片机内部的ADC采样,很有可能达不到实际采样精度,这个时候就需要外接外部ADC芯片进行采样,这些外部ADC一般都是SPI接口或者是并口。单片机通过SPI接口或并口读写芯片内部寄存器,配置参考极性、采样通道、低通滤波器带宽、基准电压源、通道序列器等。本文主要对ADI家的14bit、8通道、250k的ADC7949做一个总结,这款ADC在实际项目中使用,采样精度达到要求,读取时序有点点绕,但是是一款十分常用的ADC芯片。就是价格不太友好哈哈,一块芯片快60。
核回归(Kernel Regression)
本文讲解了核函数,并且实战通过核函数进行了预测,并附python代码
Vue3+TypeScript踩坑
type assertion expressions can only be used in TypeScript files.Vetur(8016)**
【SpringBoot笔记44】SpringBoot多数据源配置(方式一:配置多个mapper扫描不同的包路径实现多数据源配置)
在SpringBoot应用开发中,一般情况下,都是只会配置一个数据源信息,之后整个工程都是对当前数据源进行增删改查的操作。但是,在实际开发里面,也有可能会遇到多数据源的情况,例如:当前工程中除了需要访问自己应用的数据库,还需要直接连接第三方系统的数据库进行业务处理,这种情况下,就需要进行多数据源的配置。SpringBoot考虑到了这一点,所以它是支持多数据源的配置的,下面介绍一下如何配置多数据源。
typescript ts 错误列表
typescript ts 错误列表
高通平台 Android T 蓝牙技术全解析:A2DP 与 AVRCP 核心代码路径与交互流程
A2DP 接收端 - 连接流程(AVDTP 打开)
【DRAM存储器六十一】LPDDR5介绍--LPDDR5/5X/4/4X IO结构
简述LPDDR5/5X/4/4X IO结构及等效电路下的VREF理论值计算
overloaded Function in c++
The overloaded function is an important concept in C++. What's the definition? Function that have the same name but different parameter lists and that appear in the same scope are overloaded. Genera
避坑指南!YOLO26模型导出/推理常见问题,99%的开发者都踩过
版本锁定:Ultralytics=8.4.2、OpenVINO=2024.0.0、Python=3.10,版本不一致是80%问题的根源;参数对齐:训练/导出/推理的imgsz、归一化、坐标映射必须完全一致,差一步就出错;算子统一:避免自定义算子,优先用YOLO26原生算子(C3k2/PSABlock),确保推理引擎兼容;分步验证:导出后先校验ONNX/IR模型→单图片推理→RTSP流推理→72小时稳定性测试,一步过易踩坑;工业级测试。
每天进步一点点-->重载函数(overloaded function)
出现在作用域中的两个函数,如果具有相同的名字而形参表不同,则称为重载函数。 重载函数在作用域方面特别要注意: string init();// the name init has global scope void fcn() { int init = 0;//init is local and hides global init string s = init();//error
温度PID控制PLC程序
温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值
Devexpress16.2.6破解工具
Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具
TS错误信息列表
错误信息列表code类型英文描述中文描述1002错误Unterminated string literal.未终止的字符串文本。1003错误Identifier expected.应为标识符。1005错误'{0}' expected.应为“{0}”。1006错误A file cannot have a reference to itself.文件不能引用自身。1009错误Trailing comm...
计算机控制技术及应用
《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。
解决vue3+ts 创建项目其中的.vue文件出现 ‘interface‘ declarations can only be used in TypeScript files.
在首选项->设置里面打开setting.json文件删除或者注释掉下面代码, "files.associations": { ".eslintrc": "json", "*.vue": "html" }, 出现这个问题的原因可能就是一些插件之间的配置冲突什么的,反正搞得我这几个小时 是真的累了 ...
VB摄像头监控
该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制
一些常见的SQL报错
This section lists messages generated when SQL statements are parsed by the Oracle Server. Most, but not all, messages in this section indicate incorrect SQL syntax. For more information about SQL syn
Vue3+TS项目踩坑记录:Type assertion expressions can only be used in TypeScript files.
javascript.validate.enable和typescript.validate.enable
1-Control Statement
function click(){if(event.button==2) {alert(123木头人!8许动!>&<) }} function CtrlKeyDown(){if(event.ctrlKey) {alert(哇卡卡!888许动!)}}document.onkeydown=CtrlKeyDown;document.onmousedown=click; I
!!!Chapter 14 Overloaded Operations and Conversions (14.1 ~ 14.5)
14.1 Defining an Overloaded Operator Overloaded operators has a return type and a parameter list: Sales_item operator+(const Sales_item &, const Sales_item&) Normally, overloaded operator has the s
Linux centOS 7安装Redis 6.0.9步骤和make遇到的坑 解决方案
原文链接:https://blog.youkuaiyun.com/qq1130169218/article/details/106329494?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.cont
关于 overloaded function differs only by return type from 'void __thiscall 与类内实现
<br />//设计一个平面几何中的类POSITION,该类至少提供移动·求到另一点距离(包括到原点距离),求X坐标,求Y坐标的操作。<br />//出现了错误关于 overloaded function differs only by return type from 'void __thiscall<br />//错误代码如下:<br /> <br /> //设计一个平面几何中的类POSITION,该类至少提供移动·求到另一点距离(包括到原点距离),求X坐标,求Y坐标的操作。 #include <io
串口流控制(flow control)
我们在串行通讯处理中,常常看到RTS/CTS和XON/XOFF这两个选项,这就是两个流控制的选项,目前流控制主要应用于调制解调器的数据通讯中,但对普通RS232编程,了解一点这方面的知识是有好处的。那么,流控制在串行通讯中有何作用,在编制串行通讯程序怎样应用呢?这里我们就来谈谈这个问题。 1.流控制在串行通讯中的作用 这里讲到的“流”,当然指的是数据流。数据在两个串口之间传输时,常
C++ Flow of control
一般的, 我们的程序执行的顺序都是yihang
c++ 函数重载 函数模板_C ++中的函数重载
c++ 函数重载 函数模板 C ++中的函数重载 (Function Overloading in C++) If any class have multiple functions with same names but different parameters then they are said to be overloaded. Function overloading allows y...
!!!Chapter 7 Functions (7.4 ~ 7.9)
7.4 Function Declarations A function must be declared before it is called. We can declare a function separately from its definition; a function may be defined only once but may be declared multiple t
3240



被折叠的 条评论
为什么被折叠?



