Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      Arithmetic operators

      From cppreference.com
      <cpp‎ |language
       
       
      C++ language
      General topics
      Flow control
      Conditional execution statements
      Iteration statements (loops)
      Jump statements
      Functions
      Function declaration
      Lambda function expression
      inline specifier
      Dynamic exception specifications(until C++17*)
      noexcept specifier(C++11)
      Exceptions
      Namespaces
      Types
      Specifiers
      constexpr(C++11)
      consteval(C++20)
      constinit(C++20)
      Storage duration specifiers
      Initialization
      Expressions
      Alternative representations
      Literals
      Boolean -Integer -Floating-point
      Character -String -nullptr(C++11)
      User-defined(C++11)
      Utilities
      Attributes(C++11)
      Types
      typedef declaration
      Type alias declaration(C++11)
      Casts
      Memory allocation
      Classes
      Class-specific function properties
      Special member functions
      Templates
      Miscellaneous
       
      Expressions
      General
      Literals
      Operators
      Conversions
       

      Returns the result of specific arithmetic operation.

      Operator nameSyntaxPrototype examples (forclass T)
      Inside class definitionOutside class definition
      Unary plus+aT T::operator+()const;T operator+(const T& a);
      Unary minus-aT T::operator-()const;T operator-(const T& a);
      Additiona+ bT T::operator+(const T2& b)const;T operator+(const T& a,const T2& b);
      Subtractiona- bT T::operator-(const T2& b)const;T operator-(const T& a,const T2& b);
      Multiplicationa* bT T::operator*(const T2& b)const;T operator*(const T& a,const T2& b);
      Divisiona/ bT T::operator/(const T2& b)const;T operator/(const T& a,const T2& b);
      Remaindera% bT T::operator%(const T2& b)const;T operator%(const T& a,const T2& b);
      Bitwise NOT~aT T::operator~()const;T operator~(const T& a);
      Bitwise ANDa& bT T::operator&(const T2& b)const;T operator&(const T& a,const T2& b);
      Bitwise ORa| bT T::operator|(const T2& b)const;T operator|(const T& a,const T2& b);
      Bitwise XORa^ bT T::operator^(const T2& b)const;T operator^(const T& a,const T2& b);
      Bitwise left shifta<< bT T::operator<<(const T2& b)const;T operator<<(const T& a,const T2& b);
      Bitwise right shifta>> bT T::operator>>(const T2& b)const;T operator>>(const T& a,const T2& b);
      Notes
      • All operators in this table areoverloadable.
      • All built-in operators return values, and mostuser-defined overloads also return values so that the user-defined operators can be used in the same manner as the built-ins. However, in a user-defined operator overload, any type can be used as return type (includingvoid). In particular, stream insertion and stream extraction overloads ofoperator<< andoperator>> returnT&.
      • T2 can be any type includingT.

      Contents

      [edit]General explanation

      All built-in arithmetic operators compute the result of specific arithmetic operation and returns its result. The arguments are not modified.

      [edit]Conversions

      If the operand passed to a built-in arithmetic operator is integral or unscoped enumeration type, then before any other action (but after lvalue-to-rvalue conversion, if applicable), the operand undergoesintegral promotion. If an operand has array or function type,array-to-pointer andfunction-to-pointer conversions are applied.

      For the binary operators (except shifts), if the promoted operands have different types,usual arithmetic conversions are applied.

      [edit]Overflows

      Unsigned integer arithmetic is always performedmodulo 2n
      where n is the number of bits in that particular integer. E.g. forunsignedint, adding one toUINT_MAX gives0, and subtracting one from0 givesUINT_MAX.

      When signed integer arithmetic operation overflows (the result does not fit in the result type), the behavior is undefined, — the possible manifestations of such an operation include:

      • it wraps around according to the rules of the representation (typicallytwo's complement),
      • it traps — on some platforms or due to compiler options (e.g.-ftrapv in GCC and Clang),
      • it saturates to minimal or maximal value (on many DSPs),
      • it is completelyoptimized out by the compiler.

      [edit]Floating-point environment

      If#pragma STDC FENV_ACCESS is supported and set toON, all floating-point arithmetic operators obey the current floating-pointrounding direction and report floating-point arithmetic errors as specified inmath_errhandling unless part of astatic initializer (in which case floating-point exceptions are not raised and the rounding mode is to nearest).

      [edit]Floating-point contraction

      Unless#pragma STDC FP_CONTRACT is supported and set toOFF, all floating-point arithmetic may be performed as if the intermediate results have infinite range and precision, that is, optimizations that omit rounding errors and floating-point exceptions are allowed. For example, C++ allows the implementation of(x* y)+ z with a single fused multiply-add CPU instruction or optimization ofa= x* x* x* x; astmp= x* x; a= tmp* tmp.

      Unrelated to contracting, intermediate results of floating-point arithmetic may have range and precision that is different from the one indicated by its type, seeFLT_EVAL_METHOD.

      Formally, the C++ standard makes no guarantee on the accuracy of floating-point operations.

      [edit]Unary arithmetic operators

      The unary arithmetic operator expressions have the form

      +expression (1)
      -expression (2)
      1) Unary plus (promotion).
      2) Unary minus (negation).

      Unary+ and- operators have higherprecedence than all binary arithmetic operators, soexpression cannot contain top-level binary arithmetic operators. These operators associate from right to left:

      +a- b;// equivalent to (+a) - b, NOT +(a - b)-c+ d;// equivalent to (-c) + d, NOT -(c + d) +-e;// equivalent to +(-e), the unary + is a no-op if “e” is a built-in type// because any possible promotion is performed during negation already

      [edit]Built-in unary arithmetic operators

      1) For the built-in unary plus operator,expression must be a prvalue of arithmetic, unscoped enumeration, or pointer type. Integral promotion is performed onexpression if it has integral or unscoped enumeration type. The type of the result is the (possibly promoted) type ofexpression.
      The result of the built-in promotion is the value ofexpression. The built-in unary operation is no-op if the operand is a prvalue of a promoted integral type or a pointer type. Otherwise, the type or value category of the operand is changed by integral promotion or lvalue-to-rvalue, array-to-pointer, function-to-pointer, or user-defined conversion. For example,char is converted toint, and non-generic capturelesslambda expression is converted to function pointer(since C++11) in unary plus expressions.
      2) For the built-in unary minus operator,expression must be a prvalue of arithmetic or unscoped enumeration type. Integral promotion is performed onexpression. The type of the result is the type of the promoted type ofexpression.
      The result of the built-in negation is the negative of the promotedexpression. For unsigneda, the value of-a is\({\small 2^N-a}\)2N
      -a
      , whereN is the number of bits after promotion.
      • In other words, the result is the two’s complement of the operand (where operand and result are considered as unsigned).

      [edit]Overloads

      Inoverload resolution against user-defined operators, for every cv-unqualified promoted arithmetic typeA and for every typeT, the following function signatures participate in overload resolution:

      A operator+(A)
      T* operator+(T*)
      A operator-(A)
      Run this code
      #include <iostream> int main(){char c=0x6a;int n1=1;unsignedchar n2=1;unsignedint n3=1;std::cout<<"char: "<< c<<" int: "<<+c<<"\n""-1, where 1 is signed: "<<-n1<<"\n""-1, where 1 is unsigned char: "<<-n2<<"\n""-1, where 1 is unsigned int: "<<-n3<<'\n';char a[3];std::cout<<"size of array: "<< sizeof a<<"\n""size of pointer: "<< sizeof+a<<'\n';}

      Possible output:

      char: j int: 106-1, where 1 is signed: -1-1, where 1 is unsigned char: -1-1, where 1 is unsigned int: 4294967295size of array: 3size of pointer: 8

      [edit]Additive operators

      The additive operator expressions have the form

      lhs+rhs (1)
      lhs-rhs (2)
      1) Binary plus (addition).
      2) Binary minus (subtraction).

      Binary+ and- operators have higherprecedence than all other binary arithmetic operators except*,/ and%. These operators associate from left to right:

      a+ b* c;// equivalent to a + (b * c),  NOT (a + b) * cd/ e- f;// equivalent to (d / e) - f,  NOT d / (e - f)g+ h>> i;// equivalent to (g + h) >> i, NOT g + (h >> i) j- k+ l- m;// equivalent to ((j - k) + l) - m

      [edit]Built-in additive operators

      For built-in binary plus and binary minus operators, both oflhs andrhs must be prvalues, and one of the following conditions must be satisfied:

      • Both operands have arithmetic or unscoped enumeration type. In this case,usual arithmetic conversions are performed on both operands.
      • Exactly one operand has integral or unscoped enumeration type. In this case, integral promotion is applied to that operand.

      In the remaining description in this section, "operand(s)",lhs andrhs refer to the converted or promoted operand(s).

      1) For built-in addition, one of the following conditions must be satisfied:
      • Both operands have arithmetic type. In this case, the result is the sum of the operands.
      • One operand is a pointer to a completely-defined object type, and the other operand has integral type. In this case, the integral value is added to the pointer (seepointer arithmetic).
      2) For built-in subtraction, one of the following conditions must be satisfied:
      • Both operands have arithmetic type. In this case, the result is the difference resulting from the subtraction ofrhs fromlhs.
      • lhs is a pointer to a completely-defined object type, andrhs has integral type. In this case, the integral value is subtracted from the pointer (seepointer arithmetic).
      • Both operands are pointers to cv-qualified or cv-unqualified versions of the same completely-defined object type. In this caserhs is subtracted fromlhs (seepointer arithmetic).

      If both operands have a floating-point type, and the type supports IEEE floating-point arithmetic (seestd::numeric_limits::is_iec559):

      • If one operand is NaN, the result is NaN.
      • Infinity minus infinity is NaN, andFE_INVALID is raised.
      • Infinity plus the negative infinity is NaN, andFE_INVALID is raised.

      [edit]Pointer arithmetic

      When an expressionJ that has integral type is added to or subtracted from an expressionP of pointer type, the result has the type ofP.

      • IfP evaluates to anull pointer value andJ evaluates to0, the result is a null pointer value.
      • Otherwise, ifP points to theith element of an array objectx withn elements, given the value ofJ asj,P is added or subtracted as follows:
      • The expressionsP+ J andJ+ P
      • point to thei+jth element ofx ifi+ j is in[0n), and
      • are pointers past the end of the last element ofx ifi+ j isn.
      • The expressionP- J
      • points to thei-jth element ofx ifi- j is in[0n), and
      • is a pointer past the end of the last element ofx ifi- j isn.
      • Otherj values result in undefined behavior.
      • Otherwise, ifP points to a complete object, a base class subobject or a member subobjecty, given the value ofJ asj,P is added or subtracted as follows:
      • The expressionsP+ J andJ+ P
      • point toy ifj is0, and
      • are pointers past the end ofy ifj is1.
      • The expressionP- J
      • points toy ifj is0, and
      • is a pointer past the end ofy ifj is-1.
      • Otherj values result in undefined behavior.
      • Otherwise, ifP is a pointer past the end of an objectz, given the value ofJ asj:
      • Ifz is an array object withn elements,P is added or subtracted as follows:
      • The expressionsP+ J andJ+ P
      • point to then+jth element ofz ifn+ j is in[0n), and
      • are pointers past the end of the last element ofz ifj is0.
      • The expressionP- J
      • points to then-jth element ofz ifn- j is in[0n), and
      • is a pointer past the end of the last element ofz ifj is0.
      • Otherj values result in undefined behavior.
      • Otherwise,P is added or subtracted as follows:
      • The expressionsP+ J andJ+ P
      • point toz ifj is-1, and
      • are pointers past the end ofz ifj is0.
      • The expressionP- J
      • points toz ifj is1, and
      • is a pointer past the end ofz ifj is0.
      • Otherj values result in undefined behavior.
      • Otherwise, the behavior is undefined.

      When two pointer expressionsP andQ are subtracted, the type of the result isstd::ptrdiff_t.

      • IfP andQ both evaluate tonull pointer values, the result is0.
      • Otherwise, ifP andQ point to, respectively, theith andjth array elements of the same array objectx, the expressionP- Q has the valuei − j.
      • Ifi − j is not representable bystd::ptrdiff_t, the behavior is undefined.
      • Otherwise, ifP andQ point to the same complete object, base class subobject or member subobject, the result is0.
      • Otherwise, the behavior is undefined.

      These pointer arithmetic operators allow pointers to satisfy theLegacyRandomAccessIterator requirements.

      For addition and subtraction, ifP orQ have type “pointer to (possibly cv-qualified)T”, whereT and the array element type are notsimilar, the behavior is undefined:

      int arr[5]={1,2,3,4,5};unsignedint*p=reinterpret_cast<unsignedint*>(arr+1);unsignedint k=*p;// OK, the value of “k” is 2unsignedint*q= p+1;// undefined behavior: “p” points to int, not unsigned int

      [edit]Overloads

      Inoverload resolution against user-defined operators, for every pair of promoted arithmetic typesL andR and for every object typeT, the following function signatures participate in overload resolution:

      LR operator+(L, R)
      LR operator-(L, R)
      T* operator+(T*,std::ptrdiff_t)
      T* operator+(std::ptrdiff_t, T*)
      T* operator-(T*,std::ptrdiff_t)
      std::ptrdiff_t operator-(T*, T*)

      whereLR is the result ofusual arithmetic conversions onL andR.

      Run this code
      #include <iostream> int main(){char c=2;unsignedint un=2;int n=-10;std::cout<<" 2 + (-10), where 2 is a char    = "<< c+ n<<"\n"" 2 + (-10), where 2 is unsigned  = "<< un+ n<<"\n"" -10 - 2.12  = "<< n-2.12<<'\n'; char a[4]={'a','b','c','d'};char* p=&a[1];std::cout<<"Pointer addition examples: "<<*p<<*(p+2)<<*(2+ p)<<*(p-1)<<'\n';char* p2=&a[4];std::cout<<"Pointer difference: "<< p2- p<<'\n';}

      Output:

       2 + (-10), where 2 is a char    = -8 2 + (-10), where 2 is unsigned  = 4294967288 -10 - 2.12  = -12.12Pointer addition examples: bddaPointer difference: 3

      [edit]Multiplicative operators

      The multiplicative operator expressions have the form

      lhs*rhs (1)
      lhs/rhs (2)
      lhs%rhs (3)
      1) Multiplication.
      2) Division.
      3) Remainder.

      Multiplicative operators have higherprecedence than all other binary arithmetic operators. These operators associate from left to right:

      a+ b* c;// equivalent to a + (b * c),  NOT (a + b) * cd/ e- f;// equivalent to (d / e) - f,  NOT d / (e - f)g% h>> i;// equivalent to (g % h) >> i, NOT g % (h >> i) j* k/ l% m;// equivalent to ((j * k) / l) % m

      [edit]Built-in multiplicative operators

      For built-in multiplication and division operators, both operands must have arithmetic or unscoped enumeration type. For the built-in remainder operator, both operands must have integral or unscoped enumeration type.Usual arithmetic conversions are performed on both operands.

      In the remaining description in this section, "operand(s)",lhs andrhs refer to the converted operand(s).

      1) The result of built-in multiplication is the product of the operands.
      If both operands have a floating-point type, and the type supports IEEE floating-point arithmetic (seestd::numeric_limits::is_iec559):
      • Multiplication of a NaN by any number gives NaN.
      • Multiplication of infinity by zero gives NaN andFE_INVALID is raised.
      2) The result of built-in division islhs divided byrhs. Ifrhs is zero, the behavior is undefined.
      If both operands have an integral type, the result is the algebraic quotient (performs integer division): the quotient is truncated towards zero (fractional part is discarded).
      If both operands have a floating-point type, and the type supports IEEE floating-point arithmetic (seestd::numeric_limits::is_iec559):
      • If one operand is NaN, the result is NaN.
      • Dividing a non-zero number by ±0.0 gives the correctly-signed infinity andFE_DIVBYZERO is raised.
      • Dividing 0.0 by 0.0 gives NaN andFE_INVALID is raised.
      3) The result of built-in remainder is the remainder of the integer division oflhs byrhs. Ifrhs is zero, the behavior is undefined.
      Ifa/ b is representable in the result type,(a/ b)* b+ a% b== a.
      Ifa/ b is not representable in the result type, the behavior of botha/ b anda% b is undefined (that meansINT_MIN%-1 is undefined on two's complement systems).

      Note: UntilCWG issue 614 was resolved (N2757), if one or both operands to binary operator % were negative, the sign of the remainder was implementation-defined, as it depends on the rounding direction of integer division. The functionstd::div provided well-defined behavior in that case.

      Note: for floating-point remainder, seestd::remainder andstd::fmod.

      [edit]Overloads

      Inoverload resolution against user-defined operators, for every pair of promoted arithmetic typesLA andRA and for every pair of promoted integral typesLI andRI the following function signatures participate in overload resolution:

      LRA operator*(LA, RA)
      LRA operator/(LA, RA)
      LRI operator%(LI, RI)

      whereLRx is the result ofusual arithmetic conversions onLx andRx.

      Run this code
      #include <iostream> int main(){char c=2;unsignedint un=2;int  n=-10;std::cout<<"2 * (-10), where 2 is a char    = "<< c* n<<"\n""2 * (-10), where 2 is unsigned  = "<< un* n<<"\n""-10 / 2.12  = "<< n/2.12<<"\n""-10 / 21  = "<< n/21<<"\n""-10 % 21  = "<< n%21<<'\n';}

      Output:

      2 * (-10), where 2 is a char    = -202 * (-10), where 2 is unsigned  = 4294967276-10 / 2.12  = -4.71698-10 / 21  = 0-10 % 21  = -10

      [edit]Bitwise logic operators

      The bitwise logic operator expressions have the form

      ~rhs (1)
      lhs&rhs (2)
      lhs|rhs (3)
      lhs^rhs (4)
      1) Bitwise NOT.
      2) Bitwise AND.
      3) Bitwise OR.
      4) Bitwise XOR.

      The bitwise NOT operator has higherprecedence than all binary arithmetic operators. It associates from right to left:

      ~a- b;// equivalent to (~a) - b, NOT ~(a - b)~c* d;// equivalent to (~c) * d, NOT ~(c * d) ~-e;// equivalent to ~(-e)

      There is an ambiguity in the grammar when~ is followed by atype name ordecltype specifier(since C++11): it can either be operator~ or start adestructor identifier). The ambiguity is resolved by treating~ as operator~.~ can start a destructor identifier only in places where forming an operator~ is syntactically invalid.

      All other bitwise logic operators have lowerprecedence than all other binary arithmetic operators. Bitwise AND has higher precedence than bitwise XOR, which has higher precedence than bitwise OR. They associate from left to right:

      a& b* c;// equivalent to a & (b * c),  NOT (a & b) * cd/ e^ f;// equivalent to (d / e) ^ f,  NOT d / (e ^ f)g<< h| i;// equivalent to (g << h) | i, NOT g << (h | i) j& k& l;// equivalent to (j & k) & lm| n^ o// equivalent to m | (n ^ o)

      [edit]Built-in bitwise logic operators

      For the built-in bitwise NOT operator,rhs must be a prvalue of integral or unscoped enumeration type, and integral promotion is performed onrhs. For other built-in bitwise logic operators, both operands must have integral or unscoped enumeration type, andusual arithmetic conversions are performed on both operands.

      In the remaining description in this section, "operand(s)",lhs andrhs refer to the converted or promoted operand(s).

      1) Given the operand asx and the result of the built-in bitwise NOT operation asr. For each coefficientx_i of the base-2 representation ofx, the corresponding coefficientr_i of the base-2 representation ofr is1 ifx_i is0, and0 otherwise.
      • In other words, the result is the one’s complement of the operand (where operand and result are considered as unsigned).
      The type of the resultr is the type of the operandx.
      2-4) Given the operands asx andy respectively and the result of the built-in binary bitwise logic operations asr. For each pair of coefficientsx_i andy_i of the base-2 representations ofx andy respectively, the corresponding coefficientr_i of the base-2 representation ofr is
      2)1 if bothx_i andy_i are1, and0 otherwise.
      3)1 if at least one ofx_i andy_i is1, and0 otherwise.
      4)1 if either (but not both) ofx_i andy_i is1, and0 otherwise.
      The type of the resultr is the type of the operandsx andy.

      [edit]Overloads

      Inoverload resolution against user-defined operators, for every pair of promoted integral typesL andR the following function signatures participate in overload resolution:

      R operator~(R)
      LR operator&(L, R)
      LR operator^(L, R)
      LR operator|(L, R)

      whereLR is the result ofusual arithmetic conversions onL andR.

      Run this code
      #include <bitset>#include <cstdint>#include <iomanip>#include <iostream> int main(){std::uint16_t mask=0x00f0;std::uint32_t x0=0x12345678;std::uint32_t x1= x0| mask;std::uint32_t x2= x0& ~mask;std::uint32_t x3= x0& mask;std::uint32_t x4= x0^ mask;std::uint32_t x5= ~x0;using bin16=std::bitset<16>;using bin32=std::bitset<32>;std::cout<<std::hex<<std::showbase<<"Mask: "<< mask<<std::setw(49)<< bin16(mask)<<"\n""Value: "<< x0<<std::setw(42)<< bin32(x0)<<"\n""Setting bits: "<< x1<<std::setw(35)<< bin32(x1)<<"\n""Clearing bits: "<< x2<<std::setw(34)<< bin32(x2)<<"\n""Selecting bits: "<< x3<<std::setw(39)<< bin32(x3)<<"\n""XOR-ing bits: "<< x4<<std::setw(35)<< bin32(x4)<<"\n""Inverting bits: "<< x5<<std::setw(33)<< bin32(x5)<<'\n';}

      Output:

      Mask: 0xf0                                 0000000011110000Value: 0x12345678          00010010001101000101011001111000Setting bits: 0x123456f8   00010010001101000101011011111000Clearing bits: 0x12345608  00010010001101000101011000001000Selecting bits: 0x70       00000000000000000000000001110000XOR-ing bits: 0x12345688   00010010001101000101011010001000Inverting bits: 0xedcba987 11101101110010111010100110000111

      [edit]Bitwise shift operators

      The bitwise shift operator expressions have the form

      lhs<<rhs (1)
      lhs>>rhs (2)
      1) Bitwise left-shift.
      2) Bitwise right-shift.

      Bitwise shift operators have higherprecedence than bitwise logic operators, but have lower precedence than additive and multiplicative operators. These operators associate from left to right:

      a>> b* c;// equivalent to a >> (b * c),  NOT (a >> b) * cd<< e& f;// equivalent to (d << e) & f,  NOT d << (e & f) g<< h>> i;// equivalent to (g << h) >> i, NOT g << (h >> i)

      [edit]Built-in bitwise shift operators

      For the built-in bitwise shift operators, both operands must be prvalues of integral or unscoped enumeration type. Integral promotions are performed on both operands.

      In the remaining description in this section, "operand(s)",a,b,lhs andrhs refer to the converted or promoted operand(s).

      If the value ofrhs is negative or is not less than the number of bits inlhs, the behavior is undefined.

      For unsigneda, the value ofa<< b is the value ofa * 2b
      , reduced modulo2N
      where N is the number of bits in the return type (that is, bitwise left shift is performed and the bits that get shifted out of the destination type are discarded).

      For signed and non-negativea, ifa * 2b
      is representable in the unsigned version of the return type, then that value,converted to signed, is the value ofa<< b (this makes it legal to createINT_MIN as1<<31); otherwise the behavior is undefined.

      For negativea, the behavior ofa<< b is undefined.

      For unsigneda and for signed and non-negativea, the value ofa>> b is the integer part ofa/2b
      .

      For negativea, the value ofa>> b is implementation-defined (in most implementations, this performs arithmetic right shift, so that the result remains negative).

      (until C++20)

      The value ofa<< b is the unique value congruent toa * 2b
      modulo2N
      where N is the number of bits in the return type (that is, bitwise left shift is performed and the bits that get shifted out of the destination type are discarded).

      The value ofa>> b isa/2b
      , rounded towards negative infinity (in other words, right shift on signeda is arithmetic right shift).

      (since C++20)

      The type of the result is that oflhs.

      [edit]Overloads

      Inoverload resolution against user-defined operators, for every pair of promoted integral typesL andR, the following function signatures participate in overload resolution:

      L operator<<(L, R)
      L operator>>(L, R)
      Run this code
      #include <iostream> enum{ ONE=1, TWO=2}; int main(){std::cout<<std::hex<<std::showbase;char c=0x10;unsignedlonglong ull=0x123;std::cout<<"0x123 << 1 = "<<(ull<<1)<<"\n""0x123 << 63 = "<<(ull<<63)<<"\n"// overflow in unsigned"0x10 << 10 = "<<(c<<10)<<'\n';// char is promoted to intlonglong ll=-1000;std::cout<<std::dec<<"-1000 >> 1 = "<<(ll>> ONE)<<'\n';}

      Output:

      0x123 << 1 = 0x2460x123 << 63 = 0x80000000000000000x10 << 10 = 0x4000-1000 >> 1 = -500

      [edit]Standard library

      Arithmetic operators are overloaded for many standard library types.

      [edit]Unary arithmetic operators

      implements unary + and unary -
      (public member function ofstd::chrono::duration<Rep,Period>)[edit]
      applies unary operators to complex numbers
      (function template)[edit]
      applies a unary arithmetic operator to each element of the valarray
      (public member function ofstd::valarray<T>)[edit]

      [edit]Additive operators

      performs add and subtract operations involving a time point
      (function template)[edit]
      implements arithmetic operations with durations as arguments
      (function template)[edit]
      adds or subtracts ayear_month_day and some number of years or months
      (function)[edit]
      concatenates two strings, a string and achar, or a string andstring_view
      (function template)[edit]
      advances or decrements the iterator
      (public member function ofstd::reverse_iterator<Iter>)
      advances or decrements the iterator
      (public member function ofstd::move_iterator<Iter>)
      performs complex number arithmetic on two complex values or a complex and a scalar
      (function template)[edit]
      applies binary operators to each element of two valarrays, or a valarray and a value
      (function template)[edit]

      [edit]Multiplicative operators

      implements arithmetic operations with durations as arguments
      (function template)[edit]
      performs complex number arithmetic on two complex values or a complex and a scalar
      (function template)[edit]
      applies binary operators to each element of two valarrays, or a valarray and a value
      (function template)[edit]

      [edit]Bitwise logic operators

      performs binary AND, OR, XOR and NOT
      (public member function ofstd::bitset<N>)[edit]
      performs binary logic operations on bitsets
      (function template)[edit]
      applies a unary arithmetic operator to each element of the valarray
      (public member function ofstd::valarray<T>)
      applies binary operators to each element of two valarrays, or a valarray and a value
      (function template)

      [edit]Bitwise shift operators

      applies binary operators to each element of two valarrays, or a valarray and a value
      (function template)
      performs binary shift left and shift right
      (public member function ofstd::bitset<N>)

      [edit]Stream insertion/extraction operators

      Throughout the standard library, bitwise shift operators are commonly overloaded with I/O stream (std::ios_base& or one of the classes derived from it) as both the left operand and return type. Such operators are known asstream insertion andstream extraction operators:

      extracts formatted data
      (public member function ofstd::basic_istream<CharT,Traits>)[edit]
      extracts characters and character arrays
      (function template)[edit]
      inserts formatted data
      (public member function ofstd::basic_ostream<CharT,Traits>)[edit]
      inserts character data or insert into rvalue stream
      (function template)[edit]
      serializes and deserializes a complex number
      (function template)[edit]
      performs stream input and output of bitsets
      (function template)[edit]
      performs stream input and output on strings
      (function template)[edit]
      performs stream input and output on pseudo-random number engine
      (function template)[edit]
      performs stream input and output on pseudo-random number distribution
      (function template)[edit]

      [edit]Defect reports

      The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

      DRApplied toBehavior as publishedCorrect behavior
      CWG 614C++98the algebraic quotient of integer division was
      rounded in implementation-defined direction
      the algebraic quotient of integer
      division is truncated towards zero
      (fractional part is discarded)
      CWG 1450C++98the result ofa/ b was unspecified if
      it is not representable in the result type
      the behavior of botha/ b and
      a% b is undefined in this case
      CWG 1457C++98the behavior of shifting the leftmost1 bit of a
      positive signed value into the sign bit was undefined
      made well-defined
      CWG 1504C++98a pointer to a base class subobject of an array
      element could be used in pointer arithmetic
      the behavior is
      undefined in this case
      CWG 1515C++98only unsigned integers which declaredunsigned
      should obey the laws of arithmeticmodulo 2n
      applies to all unsigned integers
      CWG 1642C++98arithmetic operators allow their operands to be lvaluessome operands must be rvalues
      CWG 1865C++98the resolution ofCWG issue 1504 made the behaviors
      of pointer arithmetic involving pointers to array element
      undefined if the pointed-to type and the array element
      type have different cv-qualifications in non-top levels
      made well-defined
      CWG 1971C++98it was unclear whether the rule resolving the
      ambiguity of~ applies to cases such as~X(0)
      the rule applies to such cases
      CWG 2419C++98a pointer to non-array object was only treated as a
      pointer to the first element of an array with size 1
      in pointer arithmetic if the pointer is obtained by&
      applies to all pointers
      to non-array objects
      CWG 2626C++98the result of built-inoperator~ was simply
      'one's complement' without proper definition
      the result is phrased in terms
      of the base-2 representation
      CWG 2724C++20the rounding direction of arithmetic right shift was unclearmade clear
      CWG 2853C++98a pointer past the end of an object could
      not be added or subtracted with an integer
      it can

      [edit]See also

      Operator precedence

      Operator overloading

      Common operators
      assignmentincrement
      decrement
      arithmeticlogicalcomparisonmember
      access
      other

      a= b
      a+= b
      a-= b
      a*= b
      a/= b
      a%= b
      a&= b
      a|= b
      a^= b
      a<<= b
      a>>= b

      ++a
      --a
      a++
      a--

      +a
      -a
      a+ b
      a- b
      a* b
      a/ b
      a% b
      ~a
      a& b
      a| b
      a^ b
      a<< b
      a>> b

      !a
      a&& b
      a|| b

      a== b
      a!= b
      a< b
      a> b
      a<= b
      a>= b
      a<=> b

      a[...]
      *a
      &a
      a->b
      a.b
      a->*b
      a.*b

      function call

      a(...)
      comma

      a, b
      conditional

      a? b: c
      Special operators

      static_cast converts one type to another related type
      dynamic_cast converts within inheritance hierarchies
      const_cast adds or removescv-qualifiers
      reinterpret_cast converts type to unrelated type
      C-style cast converts one type to another by a mix ofstatic_cast,const_cast, andreinterpret_cast
      new creates objects with dynamic storage duration
      delete destructs objects previously created by the new expression and releases obtained memory area
      sizeof queries the size of a type
      sizeof... queries the size of apack(since C++11)
      typeid queries the type information of a type
      noexcept checks if an expression can throw an exception(since C++11)
      alignof queries alignment requirements of a type(since C++11)

      C documentation forArithmetic operators
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/language/operator_arithmetic&oldid=172816"

      [8]ページ先頭

      ©2009-2025 Movatter.jp