为什么枚举值具有大(> int)值?

时间:2019-09-30 20:39:57

标签: c enums

我定义了这样的枚举之后:

typedef enum { x = 1ULL<<40 } e;

似乎表达式“ x”的值为1UL << 40。

但是,C11 6.4.4.3表示“声明为枚举常量的标识符的类型为int。”

因为我希望枚举值> 1 << 32,所以这可以节省我的一天。但是,我需要知道如何。编写不符合标准的代码让我有点紧张。

我尝试了以下代码:

int main() {
        printf("%zu %zu %lx\n", sizeof(e), sizeof(x), x);
        return 0;
}

使用gcc -std=c11 -Wall(gcc 8.3.1,linux x86_64)编译时,它输出:8 8 10000000000

如果将%lx更改为%llx,则会收到编译警告和相同的输出,表明x的大小很大。

根据我对规范的阅读,我希望编译警告并输出4 4 0

1 个答案:

答案 0 :(得分:3)

编译器扩展。例如,使用clang:

import * as React from "react";
import { render } from "react-dom";

import { useWindowScroll } from "react-use";

const useHeaderState = () => {
  const [headerState, setHeaderState] = React.useState(0);

  const { y } = useWindowScroll();

  React.useEffect(() => {
    if (y > 50 && headerState !== 1) {
      setHeaderState(1);
    }
  }, [y, headerState]);

  return headerState;
};

const Header: React.FC<{ headerState: number }> = React.memo(props => {
  console.log("rerender");

  return (
    <header className={props.headerState === 1 && "class"}>
      <div className="bg-gray-900 h-16 md:h-32">header</div>
    </header>
  );
});

function App() {
  const headerState = useHeaderState();

  return (
    <div style={{ height: 2000 }}>
      <Header headerState={headerState} />
    </div>
  );
}

const rootElement = document.getElementById("root");
render(<App />, rootElement);

使用gcc:

dput(head(data))
structure(list(Global_Region = structure(c(3L, 1L, 1L, 1L, 1L, 1L), .Label = c("Europe", "Middle East", "Eastern Block", "South & Central, "America", "North America", "Africa", "Asia", "Asian Pacfic"), class = "factor"), No_Elected = structure(c(2L, 2L, 2L, 2L, 2L, 2L), .Label = c("No","Yes"), class = "factor")), row.names = c(NA, 6L), class = "data.frame")

head(data)
  Global_Region No_Elected
1 Eastern Block        Yes
2        Europe        Yes
3        Europe        Yes
4        Europe        Yes
5        Europe        Yes
6        Europe        Yes