美文网首页
C 运算符 / static / type conversion

C 运算符 / static / type conversion

作者: my_passion | 来源:发表于2020-03-23 23:27 被阅读0次

1 运算符 及其 优先级

括号表达式 ()

取成员. ->

取下标 [] / 函数调用 / 后置递增减(++ --) / 运行时类型检查 typeid / C++风格的4种显示强转

单目: ! ~ & * 前置递增减(++ --) sizeof C风格强转 (type) expr / new/delete相关

算术 * / %
   + -

移位 << >>

关系 < <= > >=
   == !=

&
   ^
   |

逻辑 &&
   ||

条件 ? :

赋值 = +=

逗号 ,

(1) 自右向左 结合: 单目 / 条件 / 赋值

同级时, 3 种 

(2) 计算顺序 由 compiler 决定 的 case

1) x = f() + g() // 先 f() 还是 g()

`C 不指定 同一运算符 左/右 操作数 计算顺序`
2) printf("%d %d \n", ++n, n); // 先 ++n 还是 先 n

(3) 单目 * ++ 同级 => 看 结合方向: 从右向左 结合

*p++ == *(p++) <=> *p; p++;

`拆成2行语句分析: 常用于 循环临界`
// eg1
val =  *p++;  
//<=>
val = *p;
p++;

*p == '\0' 时, 直接跳出循环, 不再执行 p++

// eg2
while(*p++ != '\0')  
    ;
//<=>
while(*p != '\0')
    p++;
(4) %
结果 `与 左 同号`   45%-7 = 3
(5) 关系 / 逻辑 expr 值为
1, `条件` True
0,        False

if  while  for 中 `条件` 可以是 `关系 / 逻辑 表达式`

if(! var)  <=> if(var == 0)
if(  var)  <=> if(var != 0)
(6) 条件

(n > 0) ? f : n;  // float f;  int n;

类型转换 时, expr type 为 double, 无论 n>0 是否成立
(7) 赋值
1) `值为` 赋值后 `左边的值`
x = 2;
x*= (y = z = 5) 
<=> 
x *= (y = (z = 5)) 
<=>
z = 5;
y = z;
x = x *y;
2) `一种习惯`

`赋值表达式作为一个整体`  出现在  `一个表达式的某一部分`
int c;
while( ( c = getchar() ) != EOF )
{
    putchar();
}
3) i += 2 比 i = i + 2 效率高
i += 2    // `把2加到i`
i = i + 2 // 取 i, 加上2,结果放回 i
(8) 逗号

值是 `the last expr` 的值

2 变量

1. register

不能 用 & 取地址
2. static : 2 类 3 种用法

(1) 延长生存期整个程序运行期间

1) static local variable

`初次 / 以后` 进入 func ( block ) 时, 
`初始化 ( 只 1 次 ) 为 垃圾值` / 用 `上次 函数调用 结束的值`

(2) 限制作用域 至 本文件: namespace 作用

不用担心 与 other 文件 产生 `重名冲突`
1) static external variable
    初始化 为 定义处值, default = 0
2) static external func 

2.2 变量 存储区 / lifetime / scope / 初值

`静态 存储区:` 编译 / 程序结束 时, 分配 ( 初始化 1 次 )  / 释放 memory space

`动态 存储区 ( 不是 动态内存分配 heap ) :` 可视为 栈 空间
变量.jpg

3 习惯

1. 某操作的 返回值 满足某条件时, 重复执行该操作, 可简化如下

//1
c = func();
while( c != ... )
{
    c = func();
}

//2
while( ( c = func() )  != ... )
{
    ;
}

//3
int c;
c = getchar();
while( c != EOF )
{
    putchar(c);
    c = getchar();
}

//4
int c;
while( ( c = getchar() )  != EOF )
{
    putchar(c);
}
2. type / size

char  short  int  long  float  double

1) char 占 1 Byte, other 取决于 compiler
        通常  `short  int  long 占 2  4  4 Byte`

2) type 的 value scope
2^16 = 65536    
 
=> 

2^15 = 32768
2^32 = 42 9496 7276 (42亿)
3. type conversion
type conversion.jpg

implicitly conversion: 按上图
(1) 纵向: 左右 type 不同, 才转换

`横向: 必转换`

(2) -1 L > 1UL => singed long -> unsigned long: -1 变为 大整数

-1 L < 1U
unsigned int -> signed long: 1 还是 1

(3) data 不变

只是为了 本次运算需要, 产生了 data 的 suitable type
4. 形/实参 parameter / argument  

形实结合: pass by value -> copy

func 要想 modify var, 要 pass var 的 ptr / ref

相关文章

网友评论

      本文标题:C 运算符 / static / type conversion

      本文链接:https://www.haomeiwen.com/subject/ewvmyhtx.html